<commit_before><?xml version="1.0" encoding="iso-8859-1"?>
<!-- FFI docs as a chapter -->

<chapter id="ffi">
 <title>
Foreign function interface (FFI)
 </title>

  <para>GHC (mostly) conforms to the Haskell Foreign Function Interface,
  whose definition is part of the Haskell Report on <ulink url="http://www.haskell.org/"><literal>http://www.haskell.org/</literal></ulink>.</para>

  <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>
    </indexterm> flag.</para>

  <para>GHC implements a number of GHC-specific extensions to the FFI
    Addendum.  These extensions are described in <xref linkend="ffi-ghcexts" />, but please note that programs using
    these features are not portable.  Hence, these features should be
    avoided where possible.</para>

  <para>The FFI libraries are documented in the accompanying library
  documentation; see for example the
    <ulink url="&libraryBaseLocation;/Control-Concurrent.html"><literal>Foreign</literal></ulink> module.</para>

  <sect1 id="ffi-ghcexts">
    <title>GHC extensions to the FFI Addendum</title>

    <para>The FFI features that are described in this section are specific to
    GHC.  Your code will not be portable to other compilers if you use them.</para>

    <sect2>
      <title>Unboxed types</title>

      <para>The following unboxed types may be used as basic foreign types
      (see FFI Addendum, Section 3.2): <literal>Int#</literal>,
      <literal>Word#</literal>, <literal>Char#</literal>,
      <literal>Float#</literal>, <literal>Double#</literal>,
      <literal>Addr#</literal>, <literal>StablePtr# a</literal>,
      <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>,
      and <literal>ByteArray#</literal>.</para>
    </sect2>

    <sect2 id="ffi-newtype-io">
      <title>Newtype wrapping of the IO monad</title>
      <para>The FFI spec requires the IO monad to appear in various  places,
      but it can sometimes be convenient to wrap the IO monad in a
      <literal>newtype</literal>, thus:
<programlisting>
  newtype MyIO a = MIO (IO a)
</programlisting>
     (A reason for doing so might be to prevent the programmer from
	calling arbitrary IO procedures in some part of the program.)
</para>
<para>The Haskell FFI already specifies that arguments and results of
foreign imports and exports will be automatically unwrapped if they are
newtypes (Section 3.2 of the FFI addendum).  GHC extends the FFI by automatically unwrapping any newtypes that
wrap the IO monad itself.
More precisely, wherever the FFI specification requires an IO type, GHC will
accept any newtype-wrapping of an IO type.  For example, these declarations are
OK:
<programlisting>
   foreign import foo :: Int -> MyIO Int
   foreign import "dynamic" baz :: (Int -> MyIO Int) -> CInt -> MyIO Int
</programlisting>
</para>
      </sect2>

      <sect2 id="ffi-prim">
        <title>Primitive imports</title>
	<para>
	  GHC extends the FFI with an additional calling convention
	  <literal>prim</literal>, e.g.:
<programlisting>
   foreign import prim "foo" foo :: ByteArray# -> (# Int#, Int# #)
</programlisting>
	  This is used to import functions written in Cmm code that follow an
	  internal GHC calling convention. This feature is not intended for
	  use outside of the core libraries that come with GHC. For more
	  details see the GHC developer wiki.
	</para>
      </sect2>

      <sect2 id="ffi-interruptible">
        <title>Interruptible foreign calls</title>
        <para>
          This concerns the interaction of foreign calls
          with <literal>Control.Concurrent.throwTo</literal>.
          Normally when the target of a <literal>throwTo</literal> is
          involved in a foreign call, the exception is not raised
          until the call returns, and in the meantime the caller is
          blocked.  This can result in unresponsiveness, which is
          particularly undesirable in the case of user interrupt
          (e.g. Control-C).  The default behaviour when a Control-C
          signal is received (<literal>SIGINT</literal> on Unix) is to raise
          the <literal>UserInterrupt</literal> exception in the main
          thread; if the main thread is blocked in a foreign call at
          the time, then the program will not respond to the user
          interrupt.
        </para>

        <para>
          The problem is that it is not possible in general to
          interrupt a foreign call safely.  However, GHC does provide
          a way to interrupt blocking system calls which works for
          most system calls on both Unix and Windows.  When the
          <literal>InterruptibleFFI</literal> extension is enabled,
          a foreign call
          can be annotated with <literal>interruptible</literal> instead
          of <literal>safe</literal> or <literal>unsafe</literal>:

<programlisting>
foreign import ccall interruptible
   "sleep" :: CUint -> IO CUint
</programlisting>

          <literal>interruptible</literal> behaves exactly as
          <literal>safe</literal>, except that when
          a <literal>throwTo</literal> is directed at a thread in an
          interruptible foreign call, an OS-specific mechanism will be
          used to attempt to cause the foreign call to return:

          <variablelist>
            <varlistentry>
              <term>Unix systems</term>
              <listitem>
                <para>
                  The thread making the foreign call is sent
                  a <literal>SIGPIPE</literal> signal
                  using <literal>pthread_kill()</literal>.  This is
                  usually enough to cause a blocking system call to
                  return with <literal>EINTR</literal> (GHC by default
                  installs an empty signal handler
                  for <literal>SIGPIPE</literal>, to override the
                  default behaviour which is to terminate the process
                  immediately).
                </para>
              </listitem>
            </varlistentry>
            <varlistentry>
              <term>Windows systems</term>
              <listitem>
                <para>
                  [Vista and later only] The RTS calls the Win32
                  function <literal>CancelSynchronousIO</literal>,
                  which will cause a blocking I/O operation to return
                  with the
                  error <literal>ERROR_OPERATION_ABORTED</literal>.
                </para>
              </listitem>
            </varlistentry>
          </variablelist>

          If the system call is successfully interrupted, it will
          return to Haskell whereupon the exception can be raised.  Be
          especially careful when
          using <literal>interruptible</literal> that the caller of
          the foreign function is prepared to deal with the
          consequences of the call being interrupted; on Unix it is
          good practice to check for <literal>EINTR</literal> always,
          but on Windows it is not typically necessary to
          handle <literal>ERROR_OPERATION_ABORTED</literal>.
        </para>
      </sect2>

      <sect2 id="ffi-capi">
        <title>The CAPI calling convention</title>
        <para>
          The <literal>CAPI</literal> extension allows a calling
          convention of <literal>capi</literal> to be used in foreign
          declarations, e.g.

<programlisting>
foreign import capi "header.h f" f :: CInt -> IO CInt
</programlisting>

          Rather than generating code to call <literal>f</literal>
          according to the platform's ABI, we instead call
          <literal>f</literal> using the C API defined in the header
          <literal>header.h</literal>. Thus <literal>f</literal> can be
          called even if it may be defined as a CPP
          <literal>#define</literal> rather than a proper function.
        </para>

        <para>
          When using <literal>capi</literal>, it is also possible to
          import values, rather than functions. For example,

<programlisting>
foreign import capi "pi.h pi" c_pi :: CDouble
</programlisting>

          will work regardless of whether <literal>pi</literal> is
          defined as
<programlisting>
const double pi = 3.14;
</programlisting>
          or with
<programlisting>
#define pi 3.14
</programlisting>
        </para>

        <para>
          In order to tell GHC the C type that a Haskell type
          corresponds to when it is used with the CAPI, a
          <literal>CTYPE</literal> pragma can be used on the type<commit_msg>Fix copy/paste error in the docs<commit_after><?xml version="1.0" encoding="iso-8859-1"?>
<!-- FFI docs as a chapter -->

<chapter id="ffi">
 <title>
Foreign function interface (FFI)
 </title>

  <para>GHC (mostly) conforms to the Haskell Foreign Function Interface,
  whose definition is part of the Haskell Report on <ulink url="http://www.haskell.org/"><literal>http://www.haskell.org/</literal></ulink>.</para>

  <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>
    </indexterm> flag.</para>

  <para>GHC implements a number of GHC-specific extensions to the FFI
    Addendum.  These extensions are described in <xref linkend="ffi-ghcexts" />, but please note that programs using
    these features are not portable.  Hence, these features should be
    avoided where possible.</para>

  <para>The FFI libraries are documented in the accompanying library
  documentation; see for example the
    <ulink url="&libraryBaseLocation;/Control-Concurrent.html"><literal>Foreign</literal></ulink> module.</para>

  <sect1 id="ffi-ghcexts">
    <title>GHC extensions to the FFI Addendum</title>

    <para>The FFI features that are described in this section are specific to
    GHC.  Your code will not be portable to other compilers if you use them.</para>

    <sect2>
      <title>Unboxed types</title>

      <para>The following unboxed types may be used as basic foreign types
      (see FFI Addendum, Section 3.2): <literal>Int#</literal>,
      <literal>Word#</literal>, <literal>Char#</literal>,
      <literal>Float#</literal>, <literal>Double#</literal>,
      <literal>Addr#</literal>, <literal>StablePtr# a</literal>,
      <literal>MutableByteArray#</literal>, <literal>ForeignObj#</literal>,
      and <literal>ByteArray#</literal>.</para>
    </sect2>

    <sect2 id="ffi-newtype-io">
      <title>Newtype wrapping of the IO monad</title>
      <para>The FFI spec requires the IO monad to appear in various  places,
      but it can sometimes be convenient to wrap the IO monad in a
      <literal>newtype</literal>, thus:
<programlisting>
  newtype MyIO a = MIO (IO a)
</programlisting>
     (A reason for doing so might be to prevent the programmer from
	calling arbitrary IO procedures in some part of the program.)
</para>
<para>The Haskell FFI already specifies that arguments and results of
foreign imports and exports will be automatically unwrapped if they are
newtypes (Section 3.2 of the FFI addendum).  GHC extends the FFI by automatically unwrapping any newtypes that
wrap the IO monad itself.
More precisely, wherever the FFI specification requires an IO type, GHC will
accept any newtype-wrapping of an IO type.  For example, these declarations are
OK:
<programlisting>
   foreign import foo :: Int -> MyIO Int
   foreign import "dynamic" baz :: (Int -> MyIO Int) -> CInt -> MyIO Int
</programlisting>
</para>
      </sect2>

      <sect2 id="ffi-prim">
        <title>Primitive imports</title>
	<para>
	  GHC extends the FFI with an additional calling convention
	  <literal>prim</literal>, e.g.:
<programlisting>
   foreign import prim "foo" foo :: ByteArray# -> (# Int#, Int# #)
</programlisting>
	  This is used to import functions written in Cmm code that follow an
	  internal GHC calling convention. This feature is not intended for
	  use outside of the core libraries that come with GHC. For more
	  details see the GHC developer wiki.
	</para>
      </sect2>

      <sect2 id="ffi-interruptible">
        <title>Interruptible foreign calls</title>
        <para>
          This concerns the interaction of foreign calls
          with <literal>Control.Concurrent.throwTo</literal>.
          Normally when the target of a <literal>throwTo</literal> is
          involved in a foreign call, the exception is not raised
          until the call returns, and in the meantime the caller is
          blocked.  This can result in unresponsiveness, which is
          particularly undesirable in the case of user interrupt
          (e.g. Control-C).  The default behaviour when a Control-C
          signal is received (<literal>SIGINT</literal> on Unix) is to raise
          the <literal>UserInterrupt</literal> exception in the main
          thread; if the main thread is blocked in a foreign call at
          the time, then the program will not respond to the user
          interrupt.
        </para>

        <para>
          The problem is that it is not possible in general to
          interrupt a foreign call safely.  However, GHC does provide
          a way to interrupt blocking system calls which works for
          most system calls on both Unix and Windows.  When the
          <literal>InterruptibleFFI</literal> extension is enabled,
          a foreign call
          can be annotated with <literal>interruptible</literal> instead
          of <literal>safe</literal> or <literal>unsafe</literal>:

<programlisting>
foreign import ccall interruptible
   "sleep" :: CUint -> IO CUint
</programlisting>

          <literal>interruptible</literal> behaves exactly as
          <literal>safe</literal>, except that when
          a <literal>throwTo</literal> is directed at a thread in an
          interruptible foreign call, an OS-specific mechanism will be
          used to attempt to cause the foreign call to return:

          <variablelist>
            <varlistentry>
              <term>Unix systems</term>
              <listitem>
                <para>
                  The thread making the foreign call is sent
                  a <literal>SIGPIPE</literal> signal
                  using <literal>pthread_kill()</literal>.  This is
                  usually enough to cause a blocking system call to
                  return with <literal>EINTR</literal> (GHC by default
                  installs an empty signal handler
                  for <literal>SIGPIPE</literal>, to override the
                  default behaviour which is to terminate the process
                  immediately).
                </para>
              </listitem>
            </varlistentry>
            <varlistentry>
              <term>Windows systems</term>
              <listitem>
                <para>
                  [Vista and later only] The RTS calls the Win32
                  function <literal>CancelSynchronousIO</literal>,
                  which will cause a blocking I/O operation to return
                  with the
                  error <literal>ERROR_OPERATION_ABORTED</literal>.
                </para>
              </listitem>
            </varlistentry>
          </variablelist>

          If the system call is successfully interrupted, it will
          return to Haskell whereupon the exception can be raised.  Be
          especially careful when
          using <literal>interruptible</literal> that the caller of
          the foreign function is prepared to deal with the
          consequences of the call being interrupted; on Unix it is
          good practice to check for <literal>EINTR</literal> always,
          but on Windows it is not typically necessary to
          handle <literal>ERROR_OPERATION_ABORTED</literal>.
        </para>
      </sect2>

      <sect2 id="ffi-capi">
        <title>The CAPI calling convention</title>
        <para>
          The <literal>CAPI</literal> extension allows a calling
          convention of <literal>capi</literal> to be used in foreign
          declarations, e.g.

<programlisting>
foreign import capi "header.h f" f :: CInt -> IO CInt
</programlisting>

          Rather than generating code to call <literal>f</literal>
          according to the platform's ABI, we instead call
          <literal>f</literal> using the C API defined in the header
          <literal>header.h</literal>. Thus <literal>f</literal> can be
          called even if it may be defined as a CPP
          <literal>#define</literal> rather than a proper function.
        </para>

        <para>
          When using <literal>capi</literal>, it is also possible to
          import values, rather than functions. For example,

<programlisting>
foreign import capi "pi.h value pi" c_pi :: CDouble
</programlisting>

          will work regardless of whether <literal>pi</literal> is
          defined as
<programlisting>
const double pi = 3.14;
</programlisting>
          or with
<programlisting>
#define pi 3.14
</programlisting>
        </para>

        <para>
          In order to tell GHC the C type that a Haskell type
          corresponds to when it is used with the CAPI, a
          <literal>CTYPE</literal> pragma can be used on the type
{'fraction_non_alphanumeric': 0.08319458000803813, 'fraction_numerical': 0.0033300798070850317, 'mean_word_length': 2.5474541751527493, 'pattern_counts': {'":': 0, '<': 381, '<?xml version=': 2, '>': 395, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6692659', 'n_tokens_mistral': 4665, 'n_tokens_neox': 4444, 'n_words': 1855}