Document hs_init() infelicity (#2863)
[ghc-hetmet.git] / docs / users_guide / ffi-chap.xml
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <!-- FFI docs as a chapter -->
3
4 <chapter id="ffi">
5  <title>
6 Foreign function interface (FFI)
7  </title>
8
9   <para>GHC (mostly) conforms to the Haskell 98 Foreign Function Interface
10   Addendum 1.0, whose definition is available from <ulink url="http://www.haskell.org/"><literal>http://www.haskell.org/</literal></ulink>.</para>
11
12   <para>To enable FFI support in GHC, give the <option>-XForeignFunctionInterface</option><indexterm><primary><option>-XForeignFunctionInterface</option></primary>
13     </indexterm> flag.</para>
14
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>
19
20   <para>The FFI libraries are documented in the accompanying library
21   documentation; see for example the
22     <ulink url="../libraries/base/Control-Concurrent.html"><literal>Foreign</literal></ulink> module.</para>
23
24   <sect1 id="ffi-ghcexts">
25     <title>GHC extensions to the FFI Addendum</title>
26
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>
29
30     <sect2>
31       <title>Unboxed types</title>
32
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>
40     </sect2>
41
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:
47 <programlisting>
48   newtype MyIO a = MIO (IO a)
49 </programlisting>
50      (A reason for doing so might be to prevent the programmer from
51         calling arbitrary IO procedures in some part of the program.)
52 </para>
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
59 OK:
60 <programlisting>
61    foreign import foo :: Int -> MyIO Int
62    foreign import "dynamic" baz :: (Int -> MyIO Int) -> CInt -> MyIO Int
63 </programlisting>
64 </para>
65       </sect2>
66   </sect1>
67
68   <sect1 id="ffi-ghc">
69     <title>Using the FFI with GHC</title>
70
71     <para>The following sections also give some hints and tips on the
72     use of the foreign function interface in GHC.</para>
73
74     <sect2 id="foreign-export-ghc">
75       <title>Using <literal>foreign export</literal> and <literal>foreign import ccall "wrapper"</literal> with GHC</title>
76
77       <indexterm><primary><literal>foreign export
78       </literal></primary><secondary>with GHC</secondary>
79       </indexterm>
80
81       <para>When GHC compiles a module (say <filename>M.hs</filename>)
82       which uses <literal>foreign export</literal> or 
83       <literal>foreign import "wrapper"</literal>, it generates two
84       additional files, <filename>M_stub.c</filename> and
85       <filename>M_stub.h</filename>.  GHC will automatically compile
86       <filename>M_stub.c</filename> to generate
87       <filename>M_stub.o</filename> at the same time.</para>
88
89       <para>For a plain <literal>foreign export</literal>, the file
90       <filename>M_stub.h</filename> contains a C prototype for the
91       foreign exported function, and <filename>M_stub.c</filename>
92       contains its definition.  For example, if we compile the
93       following module:</para>
94
95 <programlisting>
96 module Foo where
97
98 foreign export ccall foo :: Int -> IO Int
99
100 foo :: Int -> IO Int
101 foo n = return (length (f n))
102
103 f :: Int -> [Int]
104 f 0 = []
105 f n = n:(f (n-1))</programlisting>
106
107       <para>Then <filename>Foo_stub.h</filename> will contain
108       something like this:</para>
109
110 <programlisting>
111 #include "HsFFI.h"
112 extern HsInt foo(HsInt a0);</programlisting>
113
114       <para>and <filename>Foo_stub.c</filename> contains the
115       compiler-generated definition of <literal>foo()</literal>.  To
116       invoke <literal>foo()</literal> from C, just <literal>#include
117       "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
118
119       <para>The <filename>foo_stub.c</filename> and
120         <filename>foo_stub.h</filename> files can be redirected using the
121         <option>-stubdir</option> option; see <xref linkend="options-output"
122           />.</para>
123
124       <para>When linking the program, remember to include
125         <filename>M_stub.o</filename> in the final link command line, or
126         you'll get link errors for the missing function(s) (this isn't
127         necessary when building your program with <literal>ghc
128         &ndash;&ndash;make</literal>, as GHC will automatically link in the
129         correct bits).</para>
130
131       <sect3 id="using-own-main"> 
132         <title>Using your own <literal>main()</literal></title>
133
134         <para>Normally, GHC's runtime system provides a
135         <literal>main()</literal>, which arranges to invoke
136         <literal>Main.main</literal> in the Haskell program.  However,
137         you might want to link some Haskell code into a program which
138         has a main function written in another language, say C.  In
139         order to do this, you have to initialize the Haskell runtime
140         system explicitly.</para>
141
142         <para>Let's take the example from above, and invoke it from a
143         standalone C program.  Here's the C code:</para>
144
145 <programlisting>
146 #include &lt;stdio.h&gt;
147 #include "HsFFI.h"
148
149 #ifdef __GLASGOW_HASKELL__
150 #include "foo_stub.h"
151 #endif
152
153 #ifdef __GLASGOW_HASKELL__
154 extern void __stginit_Foo ( void );
155 #endif
156
157 int main(int argc, char *argv[])
158 {
159   int i;
160
161   hs_init(&amp;argc, &amp;argv);
162 #ifdef __GLASGOW_HASKELL__
163   hs_add_root(__stginit_Foo);
164 #endif
165
166   for (i = 0; i &lt; 5; i++) {
167     printf("%d\n", foo(2500));
168   }
169
170   hs_exit();
171   return 0;
172 }</programlisting>
173
174         <para>We've surrounded the GHC-specific bits with
175         <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the
176         code should be portable across Haskell implementations that
177         support the FFI standard.</para>
178
179         <para>The call to <literal>hs_init()</literal>
180         initializes GHC's runtime system.  Do NOT try to invoke any
181         Haskell functions before calling
182         <literal>hs_init()</literal>: bad things will
183         undoubtedly happen.</para>
184
185         <para>We pass references to <literal>argc</literal> and
186         <literal>argv</literal> to <literal>hs_init()</literal>
187         so that it can separate out any arguments for the RTS
188         (i.e. those arguments between
189         <literal>+RTS...-RTS</literal>).</para>
190
191         <para>Next, we call
192         <function>hs_add_root</function><indexterm><primary><function>hs_add_root</function></primary>
193         </indexterm>, a GHC-specific interface which is required to
194         initialise the Haskell modules in the program.  The argument
195         to <function>hs_add_root</function> should be the name of the
196         initialization function for the "root" module in your program
197         - in other words, the module which directly or indirectly
198         imports all the other Haskell modules in the program.  In a
199         standalone Haskell program the root module is normally
200         <literal>Main</literal>, but when you are using Haskell code
201         from a library it may not be.  If your program has multiple
202         root modules, then you can call
203         <function>hs_add_root</function> multiple times, one for each
204         root.  The name of the initialization function for module
205         <replaceable>M</replaceable> is
206         <literal>__stginit_<replaceable>M</replaceable></literal>, and
207         it may be declared as an external function symbol as in the
208         code above.  Note that the symbol name should be transformed
209         according to the Z-encoding:</para>
210
211       <informaltable>
212         <tgroup cols="2" align="left" colsep="1" rowsep="1">
213           <thead>
214             <row>
215               <entry>Character</entry>
216               <entry>Replacement</entry>
217             </row>
218           </thead>
219           <tbody>
220             <row>
221               <entry><literal>.</literal></entry>
222               <entry><literal>zd</literal></entry>
223             </row>
224             <row>
225               <entry><literal>_</literal></entry>
226               <entry><literal>zu</literal></entry>
227             </row>
228             <row>
229               <entry><literal>`</literal></entry>
230               <entry><literal>zq</literal></entry>
231             </row>
232             <row>
233               <entry><literal>Z</literal></entry>
234               <entry><literal>ZZ</literal></entry>
235             </row>
236             <row>
237               <entry><literal>z</literal></entry>
238               <entry><literal>zz</literal></entry>
239             </row>
240           </tbody>
241         </tgroup>
242       </informaltable>
243
244         <para>After we've finished invoking our Haskell functions, we
245         can call <literal>hs_exit()</literal>, which terminates the
246         RTS.</para>
247
248         <para>There can be multiple calls to
249         <literal>hs_init()</literal>, but each one should be matched
250         by one (and only one) call to
251         <literal>hs_exit()</literal><footnote><para>The outermost
252         <literal>hs_exit()</literal> will actually de-initialise the
253         system.  NOTE that currently GHC's runtime cannot reliably
254         re-initialise after this has happened,
255         see <xref linkend="ffi-divergence" />.</para>
256         </footnote>.</para>
257
258         <para>NOTE: when linking the final program, it is normally
259         easiest to do the link using GHC, although this isn't
260         essential.  If you do use GHC, then don't forget the flag
261         <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
262           </indexterm>, otherwise GHC will try to link
263         to the <literal>Main</literal> Haskell module.</para>
264       </sect3>
265
266       <sect3 id="ffi-library">
267         <title>Making a Haskell library that can be called from foreign
268           code</title>
269
270         <para>The scenario here is much like in <xref linkend="using-own-main"
271             />, except that the aim is not to link a complete program, but to
272           make a library from Haskell code that can be deployed in the same
273           way that you would deploy a library of C code.</para>
274
275         <para>The main requirement here is that the runtime needs to be
276           initialized before any Haskell code can be called, so your library
277           should provide initialisation and deinitialisation entry points,
278           implemented in C or C++.  For example:</para>
279
280 <programlisting>
281  HsBool mylib_init(void){
282    int argc = ...
283    char *argv[] = ...
284
285    // Initialize Haskell runtime
286    hs_init(&amp;argc, &amp;argv);
287
288    // Tell Haskell about all root modules
289    hs_add_root(__stginit_Foo);
290
291    // do any other initialization here and
292    // return false if there was a problem
293    return HS_BOOL_TRUE;
294  }
295
296  void mylib_end(void){
297    hs_exit();
298  }
299 </programlisting>
300
301         <para>The initialisation routine, <literal>mylib_init</literal>, calls
302           <literal>hs_init()</literal> and <literal>hs_add_root()</literal> as
303           normal to initialise the Haskell runtime, and the corresponding
304           deinitialisation function <literal>mylib_end()</literal> calls
305           <literal>hs_exit()</literal> to shut down the runtime.</para>
306       </sect3>
307
308       <sect3 id="hs-exit">
309         <title>On the use of <literal>hs_exit()</literal></title>
310
311         <para><literal>hs_exit()</literal> normally causes the termination of
312           any running Haskell threads in the system, and when
313           <literal>hs_exit()</literal> returns, there will be no more Haskell
314           threads running.  The runtime will then shut down the system in an
315           orderly way, generating profiling
316           output and statistics if necessary, and freeing all the memory it
317           owns.</para>
318
319         <para>It isn't always possible to terminate a Haskell thread forcibly:
320           for example, the thread might be currently executing a foreign call,
321           and we have no way to force the foreign call to complete.  What's
322           more, the runtime must
323           assume that in the worst case the Haskell code and runtime are about
324           to be removed from memory (e.g. if this is a <link linkend="win32-dlls">Windows DLL</link>,
325           <literal>hs_exit()</literal> is normally called before unloading the
326           DLL).  So <literal>hs_exit()</literal> <emphasis>must</emphasis> wait
327           until all outstanding foreign calls return before it can return
328           itself.</para>
329
330         <para>The upshot of this is that if you have Haskell threads that are
331           blocked in foreign calls, then <literal>hs_exit()</literal> may hang
332           (or possibly busy-wait) until the calls return.  Therefore it's a
333           good idea to make sure you don't have any such threads in the system
334           when calling <literal>hs_exit()</literal>.  This includes any threads
335           doing I/O, because I/O may (or may not, depending on the
336           type of I/O and the platform) be implemented using blocking foreign
337           calls.</para>
338
339         <para>The GHC runtime treats program exit as a special case, to avoid
340           the need to wait for blocked threads when a standalone
341           executable exits.  Since the program and all its threads are about to
342           terminate at the same time that the code is removed from memory, it
343           isn't necessary to ensure that the threads have exited first.
344           (Unofficially, if you want to use this fast and loose version of
345           <literal>hs_exit()</literal>, then call
346           <literal>shutdownHaskellAndExit()</literal> instead).</para> 
347       </sect3>
348     </sect2>
349     
350     <sect2 id="glasgow-foreign-headers">
351       <title>Using function headers</title>
352
353       <indexterm><primary>C calls, function headers</primary></indexterm>
354
355       <para>C functions are normally declared using prototypes in a C
356         header file.  Earlier versions of GHC (6.8.3 and
357         earlier) <literal>&num;include</literal>d the header file in
358         the C source file generated from the Haskell code, and the C
359         compiler could therefore check that the C function being
360         called via the FFI was being called at the right type.</para>
361
362       <para>GHC no longer includes external header files when
363         compiling via C, so this checking is not performed.  The
364         change was made for compatibility with the native code backend
365         (<literal>-fasm</literal>) and to comply strictly with the FFI
366         specification, which requires that FFI calls are not subject
367         to macro expansion and other CPP conversions that may be
368         applied when using C header files.  This approach also
369         simplifies the inlining of foreign calls across module and
370         package boundaries: there's no need for the header file to be
371         available when compiling an inlined version of a foreign call,
372         so the compiler is free to inline foreign calls in any
373         context.</para>
374         
375       <para>The <literal>-&num;include</literal> option is now
376         deprecated, and the <literal>include-files</literal> field
377         in a Cabal package specification is ignored.</para>
378
379     </sect2>
380
381     <sect2>
382       <title>Memory Allocation</title>
383
384       <para>The FFI libraries provide several ways to allocate memory
385       for use with the FFI, and it isn't always clear which way is the
386       best.  This decision may be affected by how efficient a
387       particular kind of allocation is on a given compiler/platform,
388       so this section aims to shed some light on how the different
389       kinds of allocation perform with GHC.</para>
390
391       <variablelist>
392         <varlistentry>
393           <term><literal>alloca</literal> and friends</term>
394           <listitem>
395             <para>Useful for short-term allocation when the allocation
396             is intended to scope over a given <literal>IO</literal>
397             computation.  This kind of allocation is commonly used
398             when marshalling data to and from FFI functions.</para>
399
400             <para>In GHC, <literal>alloca</literal> is implemented
401             using <literal>MutableByteArray#</literal>, so allocation
402             and deallocation are fast: much faster than C's
403             <literal>malloc/free</literal>, but not quite as fast as
404             stack allocation in C.  Use <literal>alloca</literal>
405             whenever you can.</para>
406           </listitem>
407         </varlistentry>
408
409         <varlistentry>
410           <term><literal>mallocForeignPtr</literal></term>
411           <listitem>
412             <para>Useful for longer-term allocation which requires
413             garbage collection.  If you intend to store the pointer to
414             the memory in a foreign data structure, then
415             <literal>mallocForeignPtr</literal> is
416             <emphasis>not</emphasis> a good choice, however.</para>
417
418             <para>In GHC, <literal>mallocForeignPtr</literal> is also
419             implemented using <literal>MutableByteArray#</literal>.
420             Although the memory is pointed to by a
421             <literal>ForeignPtr</literal>, there are no actual
422             finalizers involved (unless you add one with
423             <literal>addForeignPtrFinalizer</literal>), and the
424             deallocation is done using GC, so
425             <literal>mallocForeignPtr</literal> is normally very
426             cheap.</para>
427           </listitem>
428         </varlistentry>
429
430         <varlistentry>
431           <term><literal>malloc/free</literal></term>
432           <listitem>
433             <para>If all else fails, then you need to resort to
434             <literal>Foreign.malloc</literal> and
435             <literal>Foreign.free</literal>.  These are just wrappers
436             around the C functions of the same name, and their
437             efficiency will depend ultimately on the implementations
438             of these functions in your platform's C library.  We
439             usually find <literal>malloc</literal> and
440             <literal>free</literal> to be significantly slower than
441             the other forms of allocation above.</para>
442           </listitem>
443         </varlistentry>
444
445         <varlistentry>
446           <term><literal>Foreign.Marshal.Pool</literal></term>
447           <listitem>
448             <para>Pools are currently implemented using
449             <literal>malloc/free</literal>, so while they might be a
450             more convenient way to structure your memory allocation
451             than using one of the other forms of allocation, they
452             won't be any more efficient.  We do plan to provide an
453             improved-performance implementation of Pools in the
454             future, however.</para>
455           </listitem>
456         </varlistentry>
457       </variablelist>
458     </sect2>
459   </sect1>
460 </chapter>
461
462 <!-- Emacs stuff:
463      ;;; Local Variables: ***
464      ;;; mode: xml ***
465      ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***
466      ;;; End: ***
467  -->