1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <!-- FFI docs as a chapter -->
6 Foreign function interface (FFI)
9 <para>GHC (mostly) conforms to the Haskell Foreign Function Interface,
10 whose definition is part of the Haskell Report on <ulink url="http://www.haskell.org/"><literal>http://www.haskell.org/</literal></ulink>.</para>
12 <para>FFI support is enabled by default, but can be enabled or disabled explicitly with the <option>-XForeignFunctionInterface</option><indexterm><primary><option>-XForeignFunctionInterface</option></primary>
13 </indexterm> flag.</para>
15 <para>GHC implements a number of GHC-specific extensions to the FFI
16 Addendum. These extensions are described in <xref linkend="ffi-ghcexts" />, but please note that programs using
17 these features are not portable. Hence, these features should be
18 avoided where possible.</para>
20 <para>The FFI libraries are documented in the accompanying library
21 documentation; see for example the
22 <ulink url="&libraryBaseLocation;/Control-Concurrent.html"><literal>Foreign</literal></ulink> module.</para>
24 <sect1 id="ffi-ghcexts">
25 <title>GHC extensions to the FFI Addendum</title>
27 <para>The FFI features that are described in this section are specific to
28 GHC. Your code will not be portable to other compilers if you use them.</para>
31 <title>Unboxed types</title>
33 <para>The following unboxed types may be used as basic foreign types
34 (see FFI Addendum, Section 3.2): <literal>Int#</literal>,
35 <literal>Word#</literal>, <literal>Char#</literal>,
36 <literal>Float#</literal>, <literal>Double#</literal>,
37 <literal>Addr#</literal>, <literal>StablePtr# a</literal>,
38 <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>,
39 and <literal>ByteArray#</literal>.</para>
42 <sect2 id="ffi-newtype-io">
43 <title>Newtype wrapping of the IO monad</title>
44 <para>The FFI spec requires the IO monad to appear in various places,
45 but it can sometimes be convenient to wrap the IO monad in a
46 <literal>newtype</literal>, thus:
48 newtype MyIO a = MIO (IO a)
50 (A reason for doing so might be to prevent the programmer from
51 calling arbitrary IO procedures in some part of the program.)
53 <para>The Haskell FFI already specifies that arguments and results of
54 foreign imports and exports will be automatically unwrapped if they are
55 newtypes (Section 3.2 of the FFI addendum). GHC extends the FFI by automatically unwrapping any newtypes that
56 wrap the IO monad itself.
57 More precisely, wherever the FFI specification requires an IO type, GHC will
58 accept any newtype-wrapping of an IO type. For example, these declarations are
61 foreign import foo :: Int -> MyIO Int
62 foreign import "dynamic" baz :: (Int -> MyIO Int) -> CInt -> MyIO Int
68 <title>Primitive imports</title>
70 GHC extends the FFI with an additional calling convention
71 <literal>prim</literal>, e.g.:
73 foreign import prim "foo" foo :: ByteArray# -> (# Int#, Int# #)
75 This is used to import functions written in Cmm code that follow an
76 internal GHC calling convention. This feature is not intended for
77 use outside of the core libraries that come with GHC. For more
78 details see the GHC developer wiki.
82 <sect2 id="ffi-interruptible">
83 <title>Interruptible foreign calls</title>
85 This concerns the interaction of foreign calls
86 with <literal>Control.Concurrent.throwTo</literal>.
87 Normally when the target of a <literal>throwTo</literal> is
88 involved in a foreign call, the exception is not raised
89 until the call returns, and in the meantime the caller is
90 blocked. This can result in unresponsiveness, which is
91 particularly undesirable in the case of user interrupt
92 (e.g. Control-C). The default behaviour when a Control-C
93 signal is received (<literal>SIGINT</literal> on Unix) is to raise
94 the <literal>UserInterrupt</literal> exception in the main
95 thread; if the main thread is blocked in a foreign call at
96 the time, then the program will not respond to the user
101 The problem is that it is not possible in general to
102 interrupt a foreign call safely. However, GHC does provide
103 a way to interrupt blocking system calls which works for
104 most system calls on both Unix and Windows. A foreign call
105 can be annotated with <literal>interruptible</literal> instead
106 of <literal>safe</literal> or <literal>unsafe</literal>:
109 foreign import ccall interruptible
110 "sleep" :: CUint -> IO CUint
113 <literal>interruptible</literal> behaves exactly as
114 <literal>safe</literal>, except that when
115 a <literal>throwTo</literal> is directed at a thread in an
116 interruptible foreign call, an OS-specific mechanism will be
117 used to attempt to cause the foreign call to return:
121 <term>Unix systems</term>
124 The thread making the foreign call is sent
125 a <literal>SIGPIPE</literal> signal
126 using <literal>pthread_kill()</literal>. This is
127 usually enough to cause a blocking system call to
128 return with <literal>EINTR</literal> (GHC by default
129 installs an empty signal handler
130 for <literal>SIGPIPE</literal>, to override the
131 default behaviour which is to terminate the process
137 <term>Windows systems</term>
140 [Vista and later only] The RTS calls the Win32
141 function <literal>CancelSynchronousIO</literal>,
142 which will cause a blocking I/O operation to return
144 error <literal>ERROR_OPERATION_ABORTED</literal>.
150 If the system call is successfully interrupted, it will
151 return to Haskell whereupon the exception can be raised. Be
152 especially careful when
153 using <literal>interruptible</literal> that the caller of
154 the foreign function is prepared to deal with the
155 consequences of the call being interrupted; on Unix it is
156 good practice to check for <literal>EINTR</literal> always,
157 but on Windows it is not typically necessary to
158 handle <literal>ERROR_OPERATION_ABORTED</literal>.
164 <title>Using the FFI with GHC</title>
166 <para>The following sections also give some hints and tips on the
167 use of the foreign function interface in GHC.</para>
169 <sect2 id="foreign-export-ghc">
170 <title>Using <literal>foreign export</literal> and <literal>foreign import ccall "wrapper"</literal> with GHC</title>
172 <indexterm><primary><literal>foreign export
173 </literal></primary><secondary>with GHC</secondary>
176 <para>When GHC compiles a module (say <filename>M.hs</filename>)
177 which uses <literal>foreign export</literal> or
178 <literal>foreign import "wrapper"</literal>, it generates two
179 additional files, <filename>M_stub.c</filename> and
180 <filename>M_stub.h</filename>. GHC will automatically compile
181 <filename>M_stub.c</filename> to generate
182 <filename>M_stub.o</filename> at the same time.</para>
184 <para>For a plain <literal>foreign export</literal>, the file
185 <filename>M_stub.h</filename> contains a C prototype for the
186 foreign exported function, and <filename>M_stub.c</filename>
187 contains its definition. For example, if we compile the
188 following module:</para>
193 foreign export ccall foo :: Int -> IO Int
196 foo n = return (length (f n))
200 f n = n:(f (n-1))</programlisting>
202 <para>Then <filename>Foo_stub.h</filename> will contain
203 something like this:</para>
207 extern HsInt foo(HsInt a0);</programlisting>
209 <para>and <filename>Foo_stub.c</filename> contains the
210 compiler-generated definition of <literal>foo()</literal>. To
211 invoke <literal>foo()</literal> from C, just <literal>#include
212 "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
214 <para>The <filename>foo_stub.c</filename> and
215 <filename>foo_stub.h</filename> files can be redirected using the
216 <option>-stubdir</option> option; see <xref linkend="options-output"
219 <para>When linking the program, remember to include
220 <filename>M_stub.o</filename> in the final link command line, or
221 you'll get link errors for the missing function(s) (this isn't
222 necessary when building your program with <literal>ghc
223 ––make</literal>, as GHC will automatically link in the
224 correct bits).</para>
226 <sect3 id="using-own-main">
227 <title>Using your own <literal>main()</literal></title>
229 <para>Normally, GHC's runtime system provides a
230 <literal>main()</literal>, which arranges to invoke
231 <literal>Main.main</literal> in the Haskell program. However,
232 you might want to link some Haskell code into a program which
233 has a main function written in another language, say C. In
234 order to do this, you have to initialize the Haskell runtime
235 system explicitly.</para>
237 <para>Let's take the example from above, and invoke it from a
238 standalone C program. Here's the C code:</para>
241 #include <stdio.h>
244 #ifdef __GLASGOW_HASKELL__
245 #include "foo_stub.h"
248 int main(int argc, char *argv[])
252 hs_init(&argc, &argv);
254 for (i = 0; i < 5; i++) {
255 printf("%d\n", foo(2500));
262 <para>We've surrounded the GHC-specific bits with
263 <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the
264 code should be portable across Haskell implementations that
265 support the FFI standard.</para>
267 <para>The call to <literal>hs_init()</literal>
268 initializes GHC's runtime system. Do NOT try to invoke any
269 Haskell functions before calling
270 <literal>hs_init()</literal>: bad things will
271 undoubtedly happen.</para>
273 <para>We pass references to <literal>argc</literal> and
274 <literal>argv</literal> to <literal>hs_init()</literal>
275 so that it can separate out any arguments for the RTS
276 (i.e. those arguments between
277 <literal>+RTS...-RTS</literal>).</para>
280 <tgroup cols="2" align="left" colsep="1" rowsep="1">
283 <entry>Character</entry>
284 <entry>Replacement</entry>
289 <entry><literal>.</literal></entry>
290 <entry><literal>zd</literal></entry>
293 <entry><literal>_</literal></entry>
294 <entry><literal>zu</literal></entry>
297 <entry><literal>`</literal></entry>
298 <entry><literal>zq</literal></entry>
301 <entry><literal>Z</literal></entry>
302 <entry><literal>ZZ</literal></entry>
305 <entry><literal>z</literal></entry>
306 <entry><literal>zz</literal></entry>
312 <para>After we've finished invoking our Haskell functions, we
313 can call <literal>hs_exit()</literal>, which terminates the
316 <para>There can be multiple calls to
317 <literal>hs_init()</literal>, but each one should be matched
318 by one (and only one) call to
319 <literal>hs_exit()</literal><footnote><para>The outermost
320 <literal>hs_exit()</literal> will actually de-initialise the
321 system. NOTE that currently GHC's runtime cannot reliably
322 re-initialise after this has happened,
323 see <xref linkend="ffi-divergence" />.</para>
326 <para>NOTE: when linking the final program, it is normally
327 easiest to do the link using GHC, although this isn't
328 essential. If you do use GHC, then don't forget the flag
329 <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
330 </indexterm>, otherwise GHC will try to link
331 to the <literal>Main</literal> Haskell module.</para>
334 <sect3 id="ffi-library">
335 <title>Making a Haskell library that can be called from foreign
338 <para>The scenario here is much like in <xref linkend="using-own-main"
339 />, except that the aim is not to link a complete program, but to
340 make a library from Haskell code that can be deployed in the same
341 way that you would deploy a library of C code.</para>
343 <para>The main requirement here is that the runtime needs to be
344 initialized before any Haskell code can be called, so your library
345 should provide initialisation and deinitialisation entry points,
346 implemented in C or C++. For example:</para>
349 HsBool mylib_init(void){
353 // Initialize Haskell runtime
354 hs_init(&argc, &argv);
356 // do any other initialization here and
357 // return false if there was a problem
361 void mylib_end(void){
366 <para>The initialisation routine, <literal>mylib_init</literal>, calls
367 <literal>hs_init()</literal> as
368 normal to initialise the Haskell runtime, and the corresponding
369 deinitialisation function <literal>mylib_end()</literal> calls
370 <literal>hs_exit()</literal> to shut down the runtime.</para>
375 <sect2 id="glasgow-foreign-headers">
376 <title>Using header files</title>
378 <indexterm><primary>C calls, function headers</primary></indexterm>
380 <para>C functions are normally declared using prototypes in a C
381 header file. Earlier versions of GHC (6.8.3 and
382 earlier) <literal>#include</literal>d the header file in
383 the C source file generated from the Haskell code, and the C
384 compiler could therefore check that the C function being
385 called via the FFI was being called at the right type.</para>
387 <para>GHC no longer includes external header files when
388 compiling via C, so this checking is not performed. The
389 change was made for compatibility with the native code backend
390 (<literal>-fasm</literal>) and to comply strictly with the FFI
391 specification, which requires that FFI calls are not subject
392 to macro expansion and other CPP conversions that may be
393 applied when using C header files. This approach also
394 simplifies the inlining of foreign calls across module and
395 package boundaries: there's no need for the header file to be
396 available when compiling an inlined version of a foreign call,
397 so the compiler is free to inline foreign calls in any
400 <para>The <literal>-#include</literal> option is now
401 deprecated, and the <literal>include-files</literal> field
402 in a Cabal package specification is ignored.</para>
407 <title>Memory Allocation</title>
409 <para>The FFI libraries provide several ways to allocate memory
410 for use with the FFI, and it isn't always clear which way is the
411 best. This decision may be affected by how efficient a
412 particular kind of allocation is on a given compiler/platform,
413 so this section aims to shed some light on how the different
414 kinds of allocation perform with GHC.</para>
418 <term><literal>alloca</literal> and friends</term>
420 <para>Useful for short-term allocation when the allocation
421 is intended to scope over a given <literal>IO</literal>
422 computation. This kind of allocation is commonly used
423 when marshalling data to and from FFI functions.</para>
425 <para>In GHC, <literal>alloca</literal> is implemented
426 using <literal>MutableByteArray#</literal>, so allocation
427 and deallocation are fast: much faster than C's
428 <literal>malloc/free</literal>, but not quite as fast as
429 stack allocation in C. Use <literal>alloca</literal>
430 whenever you can.</para>
435 <term><literal>mallocForeignPtr</literal></term>
437 <para>Useful for longer-term allocation which requires
438 garbage collection. If you intend to store the pointer to
439 the memory in a foreign data structure, then
440 <literal>mallocForeignPtr</literal> is
441 <emphasis>not</emphasis> a good choice, however.</para>
443 <para>In GHC, <literal>mallocForeignPtr</literal> is also
444 implemented using <literal>MutableByteArray#</literal>.
445 Although the memory is pointed to by a
446 <literal>ForeignPtr</literal>, there are no actual
447 finalizers involved (unless you add one with
448 <literal>addForeignPtrFinalizer</literal>), and the
449 deallocation is done using GC, so
450 <literal>mallocForeignPtr</literal> is normally very
456 <term><literal>malloc/free</literal></term>
458 <para>If all else fails, then you need to resort to
459 <literal>Foreign.malloc</literal> and
460 <literal>Foreign.free</literal>. These are just wrappers
461 around the C functions of the same name, and their
462 efficiency will depend ultimately on the implementations
463 of these functions in your platform's C library. We
464 usually find <literal>malloc</literal> and
465 <literal>free</literal> to be significantly slower than
466 the other forms of allocation above.</para>
471 <term><literal>Foreign.Marshal.Pool</literal></term>
473 <para>Pools are currently implemented using
474 <literal>malloc/free</literal>, so while they might be a
475 more convenient way to structure your memory allocation
476 than using one of the other forms of allocation, they
477 won't be any more efficient. We do plan to provide an
478 improved-performance implementation of Pools in the
479 future, however.</para>
485 <sect2 id="ffi-threads">
486 <title>Multi-threading and the FFI</title>
488 <para>In order to use the FFI in a multi-threaded setting, you must
489 use the <option>-threaded</option> option
490 (see <xref linkend="options-linker" />).</para>
493 <title>Foreign imports and multi-threading</title>
495 <para>When you call a <literal>foreign import</literal>ed
496 function that is annotated as <literal>safe</literal> (the
497 default), and the program was linked
498 using <option>-threaded</option>, then the call will run
499 concurrently with other running Haskell threads. If the
500 program was linked without <option>-threaded</option>,
501 then the other Haskell threads will be blocked until the
504 <para>This means that if you need to make a foreign call to
505 a function that takes a long time or blocks indefinitely,
506 then you should mark it <literal>safe</literal> and
507 use <option>-threaded</option>. Some library functions
508 make such calls internally; their documentation should
509 indicate when this is the case.</para>
511 <para>If you are making foreign calls from multiple Haskell
512 threads and using <option>-threaded</option>, make sure that
513 the foreign code you are calling is thread-safe. In
514 particularly, some GUI libraries are not thread-safe and
515 require that the caller only invokes GUI methods from a
516 single thread. If this is the case, you may need to
517 restrict your GUI operations to a single Haskell thread,
518 and possibly also use a bound thread (see
519 <xref linkend="haskell-threads-and-os-threads" />).</para>
521 <para>Note that foreign calls made by different Haskell
522 threads may execute in <emphasis>parallel</emphasis>, even
523 when the <literal>+RTS -N</literal> flag is not being used
524 (<xref linkend="parallel-options" />). The <literal>+RTS
525 -N</literal> flag controls parallel execution of Haskell
526 threads, but there may be an arbitrary number of foreign
527 calls in progress at any one time, regardless of
528 the <literal>+RTS -N</literal> value.</para>
530 <para>If a call is annotated as <literal>interruptible</literal>
531 and the program was multithreaded, the call may be
532 interrupted in the event that the Haskell thread receives an
533 exception. The mechanism by which the interrupt occurs
534 is platform dependent, but is intended to cause blocking
535 system calls to return immediately with an interrupted error
536 code. The underlying operating system thread is not to be
537 destroyed. See <xref linkend="ffi-interruptible"/> for more details.</para>
540 <sect3 id="haskell-threads-and-os-threads">
541 <title>The relationship between Haskell threads and OS
544 <para>Normally there is no fixed relationship between Haskell
545 threads and OS threads. This means that when you make a
546 foreign call, that call may take place in an unspecified OS
547 thread. Furthermore, there is no guarantee that multiple
548 calls made by one Haskell thread will be made by the same OS
551 <para>This usually isn't a problem, and it allows the GHC
552 runtime system to make efficient use of OS thread resources.
553 However, there are cases where it is useful to have more
554 control over which OS thread is used, for example when
555 calling foreign code that makes use of thread-local state.
556 For cases like this, we provide <emphasis>bound
557 threads</emphasis>, which are Haskell threads tied to a
558 particular OS thread. For information on bound threads, see
560 for the <ulink url="&libraryBaseLocation;/Control-Concurrent.html"><literal>Control.Concurrent</literal></ulink>
565 <title>Foreign exports and multi-threading</title>
567 <para>When the program is linked
568 with <option>-threaded</option>, then you may
569 invoke <literal>foreign export</literal>ed functions from
570 multiple OS threads concurrently. The runtime system must
571 be initialised as usual by
572 calling <literal>hs_init()</literal>, and this call must
573 complete before invoking any <literal>foreign
574 export</literal>ed functions.</para>
578 <title>On the use of <literal>hs_exit()</literal></title>
580 <para><literal>hs_exit()</literal> normally causes the termination of
581 any running Haskell threads in the system, and when
582 <literal>hs_exit()</literal> returns, there will be no more Haskell
583 threads running. The runtime will then shut down the system in an
584 orderly way, generating profiling
585 output and statistics if necessary, and freeing all the memory it
588 <para>It isn't always possible to terminate a Haskell thread forcibly:
589 for example, the thread might be currently executing a foreign call,
590 and we have no way to force the foreign call to complete. What's
591 more, the runtime must
592 assume that in the worst case the Haskell code and runtime are about
593 to be removed from memory (e.g. if this is a <link linkend="win32-dlls">Windows DLL</link>,
594 <literal>hs_exit()</literal> is normally called before unloading the
595 DLL). So <literal>hs_exit()</literal> <emphasis>must</emphasis> wait
596 until all outstanding foreign calls return before it can return
599 <para>The upshot of this is that if you have Haskell threads that are
600 blocked in foreign calls, then <literal>hs_exit()</literal> may hang
601 (or possibly busy-wait) until the calls return. Therefore it's a
602 good idea to make sure you don't have any such threads in the system
603 when calling <literal>hs_exit()</literal>. This includes any threads
604 doing I/O, because I/O may (or may not, depending on the
605 type of I/O and the platform) be implemented using blocking foreign
608 <para>The GHC runtime treats program exit as a special case, to avoid
609 the need to wait for blocked threads when a standalone
610 executable exits. Since the program and all its threads are about to
611 terminate at the same time that the code is removed from memory, it
612 isn't necessary to ensure that the threads have exited first.
613 (Unofficially, if you want to use this fast and loose version of
614 <literal>hs_exit()</literal>, then call
615 <literal>shutdownHaskellAndExit()</literal> instead).</para>
619 <sect2 id="ffi-floating-point">
620 <title>Floating point and the FFI</title>
623 The standard C99 <literal>fenv.h</literal> header
624 provides operations for inspecting and modifying the state of
625 the floating point unit. In particular, the rounding mode
626 used by floating point operations can be changed, and the
627 exception flags can be tested.
631 In Haskell, floating-point operations have pure types, and the
632 evaluation order is unspecified. So strictly speaking, since
633 the <literal>fenv.h</literal> functions let you change the
634 results of, or observe the effects of floating point
635 operations, use of <literal>fenv.h</literal> renders the
636 behaviour of floating-point operations anywhere in the program
641 Having said that, we <emphasis>can</emphasis> document exactly
642 what GHC does with respect to the floating point state, so
643 that if you really need to use <literal>fenv.h</literal> then
644 you can do so with full knowledge of the pitfalls:
648 GHC completely ignores the floating-point
649 environment, the runtime neither modifies nor reads it.
654 The floating-point environment is not saved over a
655 normal thread context-switch. So if you modify the
656 floating-point state in one thread, those changes may be
657 visible in other threads. Furthermore, testing the
658 exception state is not reliable, because a context
659 switch may change it. If you need to modify or test the
660 floating point state and use threads, then you must use
662 (<literal>Control.Concurrent.forkOS</literal>), because
663 a bound thread has its own OS thread, and OS threads do
664 save and restore the floating-point state.
669 It is safe to modify the floating-point unit state
670 temporarily during a foreign call, because foreign calls
671 are never pre-empted by GHC.
681 ;;; Local Variables: ***
682 ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***