Don't use old linkable for hs-boot files.
[ghc.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 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>
11
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>
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="&libraryBaseLocation;/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
67 <sect2 id="ffi-prim">
68 <title>Primitive imports</title>
69 <para>
70 GHC extends the FFI with an additional calling convention
71 <literal>prim</literal>, e.g.:
72 <programlisting>
73 foreign import prim "foo" foo :: ByteArray# -> (# Int#, Int# #)
74 </programlisting>
75 This is used to import functions written in Cmm code that follow an
76 internal GHC calling convention. The arguments and results must
77 be unboxed types, except that an argument may be of type
78 <literal>Any</literal> (by way of <literal>unsafeCoerce#</literal>)
79 and the result type is allowed to be an unboxed tuple or the
80 type <literal>Any</literal>.
81 </para>
82 <para>
83 This feature is not intended for
84 use outside of the core libraries that come with GHC. For more
85 details see the <ulink linkend="http://ghc.haskell.org/trac/ghc/wiki/Commentary/PrimOps">
86 GHC developer wiki</ulink>.
87 </para>
88 </sect2>
89
90 <sect2 id="ffi-interruptible">
91 <title>Interruptible foreign calls</title>
92 <para>
93 This concerns the interaction of foreign calls
94 with <literal>Control.Concurrent.throwTo</literal>.
95 Normally when the target of a <literal>throwTo</literal> is
96 involved in a foreign call, the exception is not raised
97 until the call returns, and in the meantime the caller is
98 blocked. This can result in unresponsiveness, which is
99 particularly undesirable in the case of user interrupt
100 (e.g. Control-C). The default behaviour when a Control-C
101 signal is received (<literal>SIGINT</literal> on Unix) is to raise
102 the <literal>UserInterrupt</literal> exception in the main
103 thread; if the main thread is blocked in a foreign call at
104 the time, then the program will not respond to the user
105 interrupt.
106 </para>
107
108 <para>
109 The problem is that it is not possible in general to
110 interrupt a foreign call safely. However, GHC does provide
111 a way to interrupt blocking system calls which works for
112 most system calls on both Unix and Windows. When the
113 <literal>InterruptibleFFI</literal> extension is enabled,
114 a foreign call
115 can be annotated with <literal>interruptible</literal> instead
116 of <literal>safe</literal> or <literal>unsafe</literal>:
117
118 <programlisting>
119 foreign import ccall interruptible
120 "sleep" sleepBlock :: CUint -> IO CUint
121 </programlisting>
122
123 <literal>interruptible</literal> behaves exactly as
124 <literal>safe</literal>, except that when
125 a <literal>throwTo</literal> is directed at a thread in an
126 interruptible foreign call, an OS-specific mechanism will be
127 used to attempt to cause the foreign call to return:
128
129 <variablelist>
130 <varlistentry>
131 <term>Unix systems</term>
132 <listitem>
133 <para>
134 The thread making the foreign call is sent
135 a <literal>SIGPIPE</literal> signal
136 using <literal>pthread_kill()</literal>. This is
137 usually enough to cause a blocking system call to
138 return with <literal>EINTR</literal> (GHC by default
139 installs an empty signal handler
140 for <literal>SIGPIPE</literal>, to override the
141 default behaviour which is to terminate the process
142 immediately).
143 </para>
144 </listitem>
145 </varlistentry>
146 <varlistentry>
147 <term>Windows systems</term>
148 <listitem>
149 <para>
150 [Vista and later only] The RTS calls the Win32
151 function <literal>CancelSynchronousIO</literal>,
152 which will cause a blocking I/O operation to return
153 with the
154 error <literal>ERROR_OPERATION_ABORTED</literal>.
155 </para>
156 </listitem>
157 </varlistentry>
158 </variablelist>
159
160 If the system call is successfully interrupted, it will
161 return to Haskell whereupon the exception can be raised. Be
162 especially careful when
163 using <literal>interruptible</literal> that the caller of
164 the foreign function is prepared to deal with the
165 consequences of the call being interrupted; on Unix it is
166 good practice to check for <literal>EINTR</literal> always,
167 but on Windows it is not typically necessary to
168 handle <literal>ERROR_OPERATION_ABORTED</literal>.
169 </para>
170 </sect2>
171
172 <sect2 id="ffi-capi">
173 <title>The CAPI calling convention</title>
174 <para>
175 The <literal>CApiFFI</literal> extension allows a calling
176 convention of <literal>capi</literal> to be used in foreign
177 declarations, e.g.
178
179 <programlisting>
180 foreign import capi "header.h f" f :: CInt -> IO CInt
181 </programlisting>
182
183 Rather than generating code to call <literal>f</literal>
184 according to the platform's ABI, we instead call
185 <literal>f</literal> using the C API defined in the header
186 <literal>header.h</literal>. Thus <literal>f</literal> can be
187 called even if it may be defined as a CPP
188 <literal>#define</literal> rather than a proper function.
189 </para>
190
191 <para>
192 When using <literal>capi</literal>, it is also possible to
193 import values, rather than functions. For example,
194
195 <programlisting>
196 foreign import capi "pi.h value pi" c_pi :: CDouble
197 </programlisting>
198
199 will work regardless of whether <literal>pi</literal> is
200 defined as
201 <programlisting>
202 const double pi = 3.14;
203 </programlisting>
204 or with
205 <programlisting>
206 #define pi 3.14
207 </programlisting>
208 </para>
209
210 <para>
211 In order to tell GHC the C type that a Haskell type
212 corresponds to when it is used with the CAPI, a
213 <literal>CTYPE</literal> pragma can be used on the type
214 definition. The header which defines the type can optionally
215 also be specified. The syntax looks like:
216
217 <programlisting>
218 data {-# CTYPE "unistd.h" "useconds_t" #-} T = ...
219 newtype {-# CTYPE "useconds_t" #-} T = ...
220 </programlisting>
221 </para>
222 </sect2>
223
224 <sect2>
225 <title><literal>hs_thread_done()</literal></title>
226
227 <programlisting>
228 void hs_thread_done(void);
229 </programlisting>
230
231 <para>
232 GHC allocates a small amount of thread-local memory when a
233 thread calls a Haskell function via a <literal>foreign
234 export</literal>. This memory is not normally freed until
235 <literal>hs_exit()</literal>; the memory is cached so that
236 subsequent calls into Haskell are fast. However, if your
237 application is long-running and repeatedly creates new
238 threads that call into Haskell, you probably want to arrange
239 that this memory is freed in those threads that have
240 finished calling Haskell functions. To do this, call
241 <literal>hs_thread_done()</literal> from the thread whose
242 memory you want to free.
243 </para>
244
245 <para>
246 Calling <literal>hs_thread_done()</literal> is entirely
247 optional. You can call it as often or as little as you
248 like. It is safe to call it from a thread that has never
249 called any Haskell functions, or one that never will. If
250 you forget to call it, the worst that can happen is that
251 some memory remains allocated until
252 <literal>hs_exit()</literal> is called. If you call it too
253 often, the worst that can happen is that the next call to a
254 Haskell function incurs some extra overhead.
255 </para>
256 </sect2>
257 </sect1>
258
259 <sect1 id="ffi-ghc">
260 <title>Using the FFI with GHC</title>
261
262 <para>The following sections also give some hints and tips on the
263 use of the foreign function interface in GHC.</para>
264
265 <sect2 id="foreign-export-ghc">
266 <title>Using <literal>foreign export</literal> and <literal>foreign import ccall "wrapper"</literal> with GHC</title>
267
268 <indexterm><primary><literal>foreign export
269 </literal></primary><secondary>with GHC</secondary>
270 </indexterm>
271
272 <para>When GHC compiles a module (say <filename>M.hs</filename>)
273 which uses <literal>foreign export</literal> or
274 <literal>foreign import "wrapper"</literal>, it generates
275 a <filename>M_stub.h</filename> for use by C programs.</para>
276
277 <para>For a plain <literal>foreign export</literal>, the file
278 <filename>M_stub.h</filename> contains a C prototype for the
279 foreign exported function. For example, if we compile the
280 following module:</para>
281
282 <programlisting>
283 module Foo where
284
285 foreign export ccall foo :: Int -> IO Int
286
287 foo :: Int -> IO Int
288 foo n = return (length (f n))
289
290 f :: Int -> [Int]
291 f 0 = []
292 f n = n:(f (n-1))</programlisting>
293
294 <para>Then <filename>Foo_stub.h</filename> will contain
295 something like this:</para>
296
297 <programlisting>
298 #include "HsFFI.h"
299 extern HsInt foo(HsInt a0);</programlisting>
300
301 <para>To invoke <literal>foo()</literal> from C, just <literal>#include
302 "Foo_stub.h"</literal> and call <literal>foo()</literal>.</para>
303
304 <para>The
305 <filename>Foo_stub.h</filename> file can be redirected using the
306 <option>-stubdir</option> option; see <xref linkend="options-output"
307 />.</para>
308
309 <sect3 id="using-own-main">
310 <title>Using your own <literal>main()</literal></title>
311
312 <para>Normally, GHC's runtime system provides a
313 <literal>main()</literal>, which arranges to invoke
314 <literal>Main.main</literal> in the Haskell program. However,
315 you might want to link some Haskell code into a program which
316 has a main function written in another language, say C. In
317 order to do this, you have to initialize the Haskell runtime
318 system explicitly.</para>
319
320 <para>Let's take the example from above, and invoke it from a
321 standalone C program. Here's the C code:</para>
322
323 <programlisting>
324 #include &lt;stdio.h&gt;
325 #include "HsFFI.h"
326
327 #ifdef __GLASGOW_HASKELL__
328 #include "Foo_stub.h"
329 #endif
330
331 int main(int argc, char *argv[])
332 {
333 int i;
334
335 hs_init(&amp;argc, &amp;argv);
336
337 for (i = 0; i &lt; 5; i++) {
338 printf("%d\n", foo(2500));
339 }
340
341 hs_exit();
342 return 0;
343 }</programlisting>
344
345 <para>We've surrounded the GHC-specific bits with
346 <literal>#ifdef __GLASGOW_HASKELL__</literal>; the rest of the
347 code should be portable across Haskell implementations that
348 support the FFI standard.</para>
349
350 <para>The call to <literal>hs_init()</literal>
351 initializes GHC's runtime system. Do NOT try to invoke any
352 Haskell functions before calling
353 <literal>hs_init()</literal>: bad things will
354 undoubtedly happen.</para>
355
356 <para>We pass references to <literal>argc</literal> and
357 <literal>argv</literal> to <literal>hs_init()</literal>
358 so that it can separate out any arguments for the RTS
359 (i.e. those arguments between
360 <literal>+RTS...-RTS</literal>).</para>
361
362 <para>After we've finished invoking our Haskell functions, we
363 can call <literal>hs_exit()</literal>, which terminates the
364 RTS.</para>
365
366 <para>There can be multiple calls to
367 <literal>hs_init()</literal>, but each one should be matched
368 by one (and only one) call to
369 <literal>hs_exit()</literal><footnote><para>The outermost
370 <literal>hs_exit()</literal> will actually de-initialise the
371 system. NOTE that currently GHC's runtime cannot reliably
372 re-initialise after this has happened,
373 see <xref linkend="infelicities-ffi" />.</para>
374 </footnote>.</para>
375
376 <para>NOTE: when linking the final program, it is normally
377 easiest to do the link using GHC, although this isn't
378 essential. If you do use GHC, then don't forget the flag
379 <option>-no-hs-main</option><indexterm><primary><option>-no-hs-main</option></primary>
380 </indexterm>, otherwise GHC will try to link
381 to the <literal>Main</literal> Haskell module.</para>
382
383 <para>To use <literal>+RTS</literal> flags
384 with <literal>hs_init()</literal>, we have to modify the
385 example slightly. By default, GHC's RTS will only accept
386 "safe"
387 <literal>+RTS</literal> flags (see
388 <xref linkend="options-linker" />), and
389 the <option>-rtsopts</option><indexterm><primary><option>-rtsopts</option></primary></indexterm> link-time flag overrides this.
390 However, <option>-rtsopts</option> has no effect
391 when <option>-no-hs-main</option> is in use (and the same
392 goes for <option>-with-rtsopts</option>). To set these
393 options we have to call a GHC-specific API instead
394 of <option>hs_init()</option>:</para>
395
396 <programlisting>
397 #include &lt;stdio.h&gt;
398 #include "HsFFI.h"
399
400 #ifdef __GLASGOW_HASKELL__
401 #include "Foo_stub.h"
402 #include "Rts.h"
403 #endif
404
405 int main(int argc, char *argv[])
406 {
407 int i;
408
409 #if __GLASGOW_HASKELL__ >= 703
410 {
411 RtsConfig conf = defaultRtsConfig;
412 conf.rts_opts_enabled = RtsOptsAll;
413 hs_init_ghc(&amp;argc, &amp;argv, conf);
414 }
415 #else
416 hs_init(&amp;argc, &amp;argv);
417 #endif
418
419 for (i = 0; i &lt; 5; i++) {
420 printf("%d\n", foo(2500));
421 }
422
423 hs_exit();
424 return 0;
425 }</programlisting>
426
427 <para>Note two changes: we included <literal>Rts.h</literal>,
428 which defines the GHC-specific external RTS interface, and we
429 called <literal>hs_init_ghc()</literal> instead
430 of <literal>hs_init()</literal>, passing an argument of
431 type <literal>RtsConfig</literal>.
432 <literal>RtsConfig</literal> is a struct with various fields
433 that affect the behaviour of the runtime system. Its
434 definition is:</para>
435
436 <programlisting>
437 typedef struct {
438 RtsOptsEnabledEnum rts_opts_enabled;
439 const char *rts_opts;
440 } RtsConfig;
441
442 extern const RtsConfig defaultRtsConfig;
443
444 typedef enum {
445 RtsOptsNone, // +RTS causes an error
446 RtsOptsSafeOnly, // safe RTS options allowed; others cause an error
447 RtsOptsAll // all RTS options allowed
448 } RtsOptsEnabledEnum;
449 </programlisting>
450
451 <para>There is a default
452 value <literal>defaultRtsConfig</literal> that should be used
453 to initialise variables of type <literal>RtsConfig</literal>.
454 More fields will undoubtedly be added
455 to <literal>RtsConfig</literal> in the future, so in order to
456 keep your code forwards-compatible it is best to initialise
457 with <literal>defaultRtsConfig</literal> and then modify the
458 required fields, as in the code sample above.</para>
459
460
461 </sect3>
462
463 <sect3 id="ffi-library">
464 <title>Making a Haskell library that can be called from foreign
465 code</title>
466
467 <para>The scenario here is much like in <xref linkend="using-own-main"
468 />, except that the aim is not to link a complete program, but to
469 make a library from Haskell code that can be deployed in the same
470 way that you would deploy a library of C code.</para>
471
472 <para>The main requirement here is that the runtime needs to be
473 initialized before any Haskell code can be called, so your library
474 should provide initialisation and deinitialisation entry points,
475 implemented in C or C++. For example:</para>
476
477 <programlisting>
478 #include &lt;stdlib.h&gt;
479 #include "HsFFI.h"
480
481 HsBool mylib_init(void){
482 int argc = 2;
483 char *argv[] = { "+RTS", "-A32m", NULL };
484 char **pargv = argv;
485
486 // Initialize Haskell runtime
487 hs_init(&amp;argc, &amp;pargv);
488
489 // do any other initialization here and
490 // return false if there was a problem
491 return HS_BOOL_TRUE;
492 }
493
494 void mylib_end(void){
495 hs_exit();
496 }
497 </programlisting>
498
499 <para>The initialisation routine, <literal>mylib_init</literal>, calls
500 <literal>hs_init()</literal> as
501 normal to initialise the Haskell runtime, and the corresponding
502 deinitialisation function <literal>mylib_end()</literal> calls
503 <literal>hs_exit()</literal> to shut down the runtime.</para>
504 </sect3>
505
506 </sect2>
507
508 <sect2 id="glasgow-foreign-headers">
509 <title>Using header files</title>
510
511 <indexterm><primary>C calls, function headers</primary></indexterm>
512
513 <para>C functions are normally declared using prototypes in a C
514 header file. Earlier versions of GHC (6.8.3 and
515 earlier) <literal>&num;include</literal>d the header file in
516 the C source file generated from the Haskell code, and the C
517 compiler could therefore check that the C function being
518 called via the FFI was being called at the right type.</para>
519
520 <para>GHC no longer includes external header files when
521 compiling via C, so this checking is not performed. The
522 change was made for compatibility with the
523 <ulink linkend="native-code-gen">native code generator</ulink>
524 (<literal>-fasm</literal>) and to comply strictly with the FFI
525 specification, which requires that FFI calls are not subject
526 to macro expansion and other CPP conversions that may be
527 applied when using C header files. This approach also
528 simplifies the inlining of foreign calls across module and
529 package boundaries: there's no need for the header file to be
530 available when compiling an inlined version of a foreign call,
531 so the compiler is free to inline foreign calls in any
532 context.</para>
533
534 <para>The <literal>-&num;include</literal> option is now
535 deprecated, and the <literal>include-files</literal> field
536 in a Cabal package specification is ignored.</para>
537
538 </sect2>
539
540 <sect2>
541 <title>Memory Allocation</title>
542
543 <para>The FFI libraries provide several ways to allocate memory
544 for use with the FFI, and it isn't always clear which way is the
545 best. This decision may be affected by how efficient a
546 particular kind of allocation is on a given compiler/platform,
547 so this section aims to shed some light on how the different
548 kinds of allocation perform with GHC.</para>
549
550 <variablelist>
551 <varlistentry>
552 <term><literal>alloca</literal> and friends</term>
553 <listitem>
554 <para>Useful for short-term allocation when the allocation
555 is intended to scope over a given <literal>IO</literal>
556 computation. This kind of allocation is commonly used
557 when marshalling data to and from FFI functions.</para>
558
559 <para>In GHC, <literal>alloca</literal> is implemented
560 using <literal>MutableByteArray#</literal>, so allocation
561 and deallocation are fast: much faster than C's
562 <literal>malloc/free</literal>, but not quite as fast as
563 stack allocation in C. Use <literal>alloca</literal>
564 whenever you can.</para>
565 </listitem>
566 </varlistentry>
567
568 <varlistentry>
569 <term><literal>mallocForeignPtr</literal></term>
570 <listitem>
571 <para>Useful for longer-term allocation which requires
572 garbage collection. If you intend to store the pointer to
573 the memory in a foreign data structure, then
574 <literal>mallocForeignPtr</literal> is
575 <emphasis>not</emphasis> a good choice, however.</para>
576
577 <para>In GHC, <literal>mallocForeignPtr</literal> is also
578 implemented using <literal>MutableByteArray#</literal>.
579 Although the memory is pointed to by a
580 <literal>ForeignPtr</literal>, there are no actual
581 finalizers involved (unless you add one with
582 <literal>addForeignPtrFinalizer</literal>), and the
583 deallocation is done using GC, so
584 <literal>mallocForeignPtr</literal> is normally very
585 cheap.</para>
586 </listitem>
587 </varlistentry>
588
589 <varlistentry>
590 <term><literal>malloc/free</literal></term>
591 <listitem>
592 <para>If all else fails, then you need to resort to
593 <literal>Foreign.malloc</literal> and
594 <literal>Foreign.free</literal>. These are just wrappers
595 around the C functions of the same name, and their
596 efficiency will depend ultimately on the implementations
597 of these functions in your platform's C library. We
598 usually find <literal>malloc</literal> and
599 <literal>free</literal> to be significantly slower than
600 the other forms of allocation above.</para>
601 </listitem>
602 </varlistentry>
603
604 <varlistentry>
605 <term><literal>Foreign.Marshal.Pool</literal></term>
606 <listitem>
607 <para>Pools are currently implemented using
608 <literal>malloc/free</literal>, so while they might be a
609 more convenient way to structure your memory allocation
610 than using one of the other forms of allocation, they
611 won't be any more efficient. We do plan to provide an
612 improved-performance implementation of Pools in the
613 future, however.</para>
614 </listitem>
615 </varlistentry>
616 </variablelist>
617 </sect2>
618
619 <sect2 id="ffi-threads">
620 <title>Multi-threading and the FFI</title>
621
622 <para>In order to use the FFI in a multi-threaded setting, you must
623 use the <option>-threaded</option> option
624 (see <xref linkend="options-linker" />).</para>
625
626 <sect3>
627 <title>Foreign imports and multi-threading</title>
628
629 <para>When you call a <literal>foreign import</literal>ed
630 function that is annotated as <literal>safe</literal> (the
631 default), and the program was linked
632 using <option>-threaded</option>, then the call will run
633 concurrently with other running Haskell threads. If the
634 program was linked without <option>-threaded</option>,
635 then the other Haskell threads will be blocked until the
636 call returns.</para>
637
638 <para>This means that if you need to make a foreign call to
639 a function that takes a long time or blocks indefinitely,
640 then you should mark it <literal>safe</literal> and
641 use <option>-threaded</option>. Some library functions
642 make such calls internally; their documentation should
643 indicate when this is the case.</para>
644
645 <para>If you are making foreign calls from multiple Haskell
646 threads and using <option>-threaded</option>, make sure that
647 the foreign code you are calling is thread-safe. In
648 particularly, some GUI libraries are not thread-safe and
649 require that the caller only invokes GUI methods from a
650 single thread. If this is the case, you may need to
651 restrict your GUI operations to a single Haskell thread,
652 and possibly also use a bound thread (see
653 <xref linkend="haskell-threads-and-os-threads" />).</para>
654
655 <para>Note that foreign calls made by different Haskell
656 threads may execute in <emphasis>parallel</emphasis>, even
657 when the <literal>+RTS -N</literal> flag is not being used
658 (<xref linkend="parallel-options" />). The <literal>+RTS
659 -N</literal> flag controls parallel execution of Haskell
660 threads, but there may be an arbitrary number of foreign
661 calls in progress at any one time, regardless of
662 the <literal>+RTS -N</literal> value.</para>
663
664 <para>If a call is annotated as <literal>interruptible</literal>
665 and the program was multithreaded, the call may be
666 interrupted in the event that the Haskell thread receives an
667 exception. The mechanism by which the interrupt occurs
668 is platform dependent, but is intended to cause blocking
669 system calls to return immediately with an interrupted error
670 code. The underlying operating system thread is not to be
671 destroyed. See <xref linkend="ffi-interruptible"/> for more details.</para>
672 </sect3>
673
674 <sect3 id="haskell-threads-and-os-threads">
675 <title>The relationship between Haskell threads and OS
676 threads</title>
677
678 <para>Normally there is no fixed relationship between Haskell
679 threads and OS threads. This means that when you make a
680 foreign call, that call may take place in an unspecified OS
681 thread. Furthermore, there is no guarantee that multiple
682 calls made by one Haskell thread will be made by the same OS
683 thread.</para>
684
685 <para>This usually isn't a problem, and it allows the GHC
686 runtime system to make efficient use of OS thread resources.
687 However, there are cases where it is useful to have more
688 control over which OS thread is used, for example when
689 calling foreign code that makes use of thread-local state.
690 For cases like this, we provide <emphasis>bound
691 threads</emphasis>, which are Haskell threads tied to a
692 particular OS thread. For information on bound threads, see
693 the documentation
694 for the <ulink url="&libraryBaseLocation;/Control-Concurrent.html"><literal>Control.Concurrent</literal></ulink>
695 module.</para>
696 </sect3>
697
698 <sect3>
699 <title>Foreign exports and multi-threading</title>
700
701 <para>When the program is linked
702 with <option>-threaded</option>, then you may
703 invoke <literal>foreign export</literal>ed functions from
704 multiple OS threads concurrently. The runtime system must
705 be initialised as usual by
706 calling <literal>hs_init()</literal>, and this call must
707 complete before invoking any <literal>foreign
708 export</literal>ed functions.</para>
709 </sect3>
710
711 <sect3 id="hs-exit">
712 <title>On the use of <literal>hs_exit()</literal></title>
713
714 <para><literal>hs_exit()</literal> normally causes the termination of
715 any running Haskell threads in the system, and when
716 <literal>hs_exit()</literal> returns, there will be no more Haskell
717 threads running. The runtime will then shut down the system in an
718 orderly way, generating profiling
719 output and statistics if necessary, and freeing all the memory it
720 owns.</para>
721
722 <para>It isn't always possible to terminate a Haskell thread forcibly:
723 for example, the thread might be currently executing a foreign call,
724 and we have no way to force the foreign call to complete. What's
725 more, the runtime must
726 assume that in the worst case the Haskell code and runtime are about
727 to be removed from memory (e.g. if this is a <link linkend="win32-dlls">Windows DLL</link>,
728 <literal>hs_exit()</literal> is normally called before unloading the
729 DLL). So <literal>hs_exit()</literal> <emphasis>must</emphasis> wait
730 until all outstanding foreign calls return before it can return
731 itself.</para>
732
733 <para>The upshot of this is that if you have Haskell threads that are
734 blocked in foreign calls, then <literal>hs_exit()</literal> may hang
735 (or possibly busy-wait) until the calls return. Therefore it's a
736 good idea to make sure you don't have any such threads in the system
737 when calling <literal>hs_exit()</literal>. This includes any threads
738 doing I/O, because I/O may (or may not, depending on the
739 type of I/O and the platform) be implemented using blocking foreign
740 calls.</para>
741
742 <para>The GHC runtime treats program exit as a special case, to avoid
743 the need to wait for blocked threads when a standalone
744 executable exits. Since the program and all its threads are about to
745 terminate at the same time that the code is removed from memory, it
746 isn't necessary to ensure that the threads have exited first.
747 (Unofficially, if you want to use this fast and loose version of
748 <literal>hs_exit()</literal>, then call
749 <literal>shutdownHaskellAndExit()</literal> instead).</para>
750 </sect3>
751 </sect2>
752
753 <sect2 id="ffi-floating-point">
754 <title>Floating point and the FFI</title>
755
756 <para>
757 The standard C99 <literal>fenv.h</literal> header
758 provides operations for inspecting and modifying the state of
759 the floating point unit. In particular, the rounding mode
760 used by floating point operations can be changed, and the
761 exception flags can be tested.
762 </para>
763
764 <para>
765 In Haskell, floating-point operations have pure types, and the
766 evaluation order is unspecified. So strictly speaking, since
767 the <literal>fenv.h</literal> functions let you change the
768 results of, or observe the effects of floating point
769 operations, use of <literal>fenv.h</literal> renders the
770 behaviour of floating-point operations anywhere in the program
771 undefined.
772 </para>
773
774 <para>
775 Having said that, we <emphasis>can</emphasis> document exactly
776 what GHC does with respect to the floating point state, so
777 that if you really need to use <literal>fenv.h</literal> then
778 you can do so with full knowledge of the pitfalls:
779 <itemizedlist>
780 <listitem>
781 <para>
782 GHC completely ignores the floating-point
783 environment, the runtime neither modifies nor reads it.
784 </para>
785 </listitem>
786 <listitem>
787 <para>
788 The floating-point environment is not saved over a
789 normal thread context-switch. So if you modify the
790 floating-point state in one thread, those changes may be
791 visible in other threads. Furthermore, testing the
792 exception state is not reliable, because a context
793 switch may change it. If you need to modify or test the
794 floating point state and use threads, then you must use
795 bound threads
796 (<literal>Control.Concurrent.forkOS</literal>), because
797 a bound thread has its own OS thread, and OS threads do
798 save and restore the floating-point state.
799 </para>
800 </listitem>
801 <listitem>
802 <para>
803 It is safe to modify the floating-point unit state
804 temporarily during a foreign call, because foreign calls
805 are never pre-empted by GHC.
806 </para>
807 </listitem>
808 </itemizedlist>
809 </para>
810 </sect2>
811 </sect1>
812 </chapter>
813
814 <!-- Emacs stuff:
815 ;;; Local Variables: ***
816 ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***
817 ;;; End: ***
818 -->