Asynchronous exceptions are fundamental to Haskell’s concurrency model, allowing us to cancel expensive operations and interrupt long-running computations by throwing an exception at the thread running them. They form the basis for common and powerful abstractions used in concurrent Haskell programs, like timeout and async’s race.

This power is significantly limited once a thread crosses the FFI boundary. A blocking foreign call sits outside the runtime’s reach by default. In 2010, the InterruptibleFFI extension was introduced to cover this gap and allow the runtime to interrupt foreign calls marked interruptible when an async exception arrives.

Unfortunately, it turns out the implementation of InterruptibleFFI has two nasty race conditions, which mean that foreign calls that are meant to be interruptible aren’t always. In this blog post, we will first give a brief introduction to how InterruptibleFFI is meant to be used, before giving an overview of the current implementation and its problems. We will describe some workarounds, and propose how the implementation can be corrected.

This is part two of our series on exceptions.

Part 1: “Exception best practices” explains the basics of synchronous and asynchronous exceptions in Haskell, and how to work with them.

Part 2: “When an interruptible call isn’t interruptible” (this blog post) discusses interruptible foreign calls: how they are meant to work, why they do not always work, and how to address that.

Part 3: “(Some) Exceptions in Haskell are resumable”, to be published soon, discusses asynchronous exceptions in pure code, resulting in resumable exceptions, and how this can easily result in poisoned thunks when we catch exceptions in “pure” code.

We’re also still planning two further parts: one on composing masking operations, and one exploring how the problems discussed in part 3 can be resolved.

Crash course in interruptible FFI

Since this is a relatively esoteric topic, let’s first take a look at what interruptible FFI even is and how it’s intended to be used, before discussing any of the problems.

Motivation

Consider this simple C function that prints one dot per second, indefinitely:

void print_dots(void) {
  struct timespec ts = { .tv_sec = 1 };
  for (;;) {
    putchar('.'); fflush(stdout);
    nanosleep(&ts, NULL);
  }
}

As Haskell programmers we are very used to the fact that we can timeout almost anything; turns out, this is not the case here:

foreign import capi safe "cbits.h print_dots" printDots :: IO ()

main :: IO ()
main = void $ timeout 2_100_000 $ printDots

This program will run until it is killed, despite the timeout.

Foreign calls: unsafe, safe, and interruptible

GHC provides several strategies for calling foreign functions, with rather distinct semantics.

A foreign call marked unsafe is little more than a direct jump into the C code. The Haskell thread holds onto its RTS capability (one of GHC’s logical CPUs) for the duration of the call, which means the GC cannot run, and no other Haskell thread on that capability gets scheduled. This is fine for short, non-blocking C calls, where the overhead of a more careful strategy would dominate the cost of the call itself, but it is unsuitable for anything that might block. If as many threads issue blocking unsafe calls as there are capabilities, the runtime makes no progress at all. Similarly, if any capability is blocked on an unsafe FFI call and we run out of space on the heap, no Haskell thread can make progress because GC cannot run until all unsafe calls have returned.

A safe call has a different set of tradeoffs. Before entering the C code, the thread invokes the RTS primitive suspendThread, which releases the capability so other Haskell threads can be scheduled while the call is in flight. The GC is free to run (so any Haskell heap data the C code touches must be pinned beforehand), and the C code is allowed to call back into Haskell. The cost is a per-call overhead from the suspend/resume dance.

Both unsafe and safe calls share a constraint: while a thread is in C it is opaque to the runtime, and queued async exceptions cannot be delivered until it returns to Haskell of its own accord. For a blocking call like nanosleep or accept, this means killThread cannot make progress until the call wakes up some other way.

interruptible is a refinement of safe for foreign calls that may block but still need to respond to cancellation. The C code runs as it would in a safe call, but if an async exception arrives while the call is in progress, the RTS attempts to abort the call by sending the OS thread a SIGPIPE signal.1

Adjusting the C call

In general, sending SIGPIPE by itself may not be enough. For our simple example, the SIGPIPE signal will cause nanosleep to return immediately, but the for loop will still continue! This means that if we run

foreign import capi interruptible "cbits.h print_dots" printDots :: IO ()

main :: IO ()
main = void $ timeout 2_100_000 $ printDots

we will see the third dot and fourth dot being printed almost at the same time (that is, one call to nanosleep got interrupted), but the program will still continue to run until killed. We must check for EINTR explicitly in the C code:

void print_dots(void) {
  struct timespec ts = { .tv_sec = 1 };
  for (;;) {
    putchar('.'); fflush(stdout);
    if (nanosleep(&ts, NULL) == -1 && errno == EINTR) break;
  }
}

Race condition

Now the timeout will mostly work, but this code has a race condition: if the signal is sent while we’re not currently blocked on that call to nanosleep, the signal will be lost: the RTS sends it only once. To make this a little more obvious, consider this version of print_dots which alternates between sleeping with nanosleep and using some kind of busy-wait spin loop:

void print_dots(void) {
  struct timespec ts = { .tv_sec = 1 };
  for (;;) {
    putchar('.'); fflush(stdout);
    if (nanosleep(&ts, NULL) == -1 && errno == EINTR) break;

    putchar('*'); fflush(stdout);
    spin(1.0);
  }
}

If SIGPIPE is sent while we’re in the spin loop, nothing happens, and the program again runs until killed. This same race condition also exists in the version that only uses nanosleep, it’s just a little less visible: the signal might arrive when calling putchar, or indeed in between any of the library calls.

Solving the race condition

Solving this race condition is possible, but difficult. One option is to install our own handler for SIGPIPE; for example, it could set some thread-local variable which we could then check in our loop:

static _Thread_local volatile sig_atomic_t interrupted;

static void on_sigpipe(int sig) {
  interrupted = 1;
}

void install_custom_handler_sigpipe(void) {
  struct sigaction sa = {.sa_handler = on_sigpipe};
  sigemptyset(&sa.sa_mask);
  sigaction(SIGPIPE, &sa, NULL);
}

void print_dots(void) {
  struct timespec ts = { .tv_sec = 1 };
  while (!interrupted) {
    putchar('.'); fflush(stdout);
    nanosleep(&ts, NULL);
    putchar('*'); fflush(stdout);
    spin(1.0);
  }
}

This works, but is of course entirely non-compositional: there is only one global SIGPIPE handler. It is also unclear when the interrupted variable should be reset; doing so without introducing new race conditions is not easy! We will see better solutions to these problems later in this blog post.

Moreover, this solution also depends on another fact: nanosleep only blocks for a bounded amount of time. Suppose SIGPIPE arrives before the call to nanosleep, but after the !interrupted check; then we will sleep, and exit when the loop comes around again. Replace nanosleep with a call that can block indefinitely, such as accept, and the race condition is back.

Asynchronous exceptions

The real question, and the topic of this blog post proper, is what happens if we do

main :: IO ()
main = void $ mask_ $ timeout 2_100_000 $ printDots

Does this still work? As we shall see, it turns out that the answer to that question is “probably, but not necessarily”.

(For a refresher on masking and interruptible operations, see the section on interruptibility in Part 1 of this series.)

InterruptibleFFI as it is implemented today

InterruptibleFFI originated with Edward Yang’s 2010 post on interrupting GHC, which made the case for letting the runtime cancel a long-running foreign call when an async exception is queued. Consider a typical case: a server thread is blocked on accept, the parent wants to shut the server down with killThread, and nothing happens because accept is sitting inside a safe foreign call. The runtime needs some way to tell the kernel that the blocked operation should return.

As we saw in the crash course, InterruptibleFFI is the language-level way to opt into this. A foreign import declaration can be marked interruptible:

foreign import ccall interruptible "accept"
    c_accept :: CInt -> Ptr () -> Ptr () -> IO CInt

The contract, as stated in the GHC user’s guide, is:

Once the system call is successfully interrupted, the surrounding code must return control out of the foreign import, back into Haskell code, so that any blocked exception can be raised if the masking state of the thread allows it. Being under mask gives the Haskell code an opportunity to detect and react to the interrupt error code from the C call.

This is essentially a safe call with one extra bit set. The wrapper GHC generates for an interruptible call looks roughly like:

token = suspendThread(BaseReg, interruptible=True);  // marks thread BlockedOnCCall_Interruptible
r = accept(fd, NULL, NULL);                          // libc
BaseReg = resumeThread(token);

If an async exception arrives for the thread while it is marked as BlockedOnCCall_Interruptible (rather than the plain BlockedOnCCall of a safe call), the RTS locates the OS thread running the C call and sends it a SIGPIPE via pthread_kill. Any blocking syscall the thread is in then aborts (typically with EINTR). GHC itself installs an empty handler for SIGPIPE by default; see #1619.

On Windows, where SIGPIPE does not exist, the runtime calls CancelSynchronousIo instead, with the same overall effect: any blocking I/O the thread is performing aborts with ERROR_OPERATION_ABORTED.

Once the C call returns, control flows back into Haskell. The queued async exception is raised as soon as the masking state of the thread allows it, and the thread unwinds as usual, allowing the user code to clean up.

At least, that is the intent. Unfortunately, this implementation suffers from a number of race conditions, as we will shortly see.

interruptible foreign calls aren’t interruptible operations

Despite the name, interruptible FFI calls are not interruptible operations (though as we will discuss later, perhaps they should be).

An interruptible operation such as takeMVar has two properties under mask:

  1. It is an interruption point: if it blocks, it raises any exception that is pending or that arrives while it is blocked.
  2. It is atomic: it either succeeds and returns its result, or it is interrupted and has had no effect.2

The second property is what makes it safe to acquire a resource with an interruptible operation:

bracket (takeMVar lock) (putMVar lock) use

If takeMVar is interrupted, bracket does not register putMVar lock. This is correct only because an interrupted takeMVar has not taken the MVar.

An interruptible foreign call is not an interruption point. Consider the following program:

foreign import ccall safe          "usleep" c_usleep :: CInt -> IO CInt
foreign import ccall interruptible "pause"  c_pause  :: IO CInt

main :: IO ()
main = do
    tid <- forkIO $ mask_ $ do
        c_usleep 200000  -- safe, 200 ms
        c_pause          -- interruptible, blocks forever

    threadDelay 50000             -- queue the exception during c_usleep
    result <- timeout 3000000 (killThread tid)
    case result of
        Just () -> exitSuccess
        Nothing -> hPutStrLn stderr "FAIL: killThread hung" >> exitFailure

The forked thread runs under mask_ and calls safe usleep for 200 ms. During that call the parent fires killThread, so by the time usleep returns a ThreadKilled exception is parked on the thread’s queue. The thread then enters the interruptible c_pause.

By analogy with takeMVar, threadDelay, and the rest of the standard library’s interruptible operations under mask_, one would expect entering c_pause to be an interruption point, raising the queued ThreadKilled. However, interruptible FFI calls are not interruptible operations! This is documented in the GHC user guide, albeit a bit obliquely:

Once the system call is successfully interrupted, the surrounding code must return control out of the foreign import, back into Haskell code, so that any blocked exception can be raised if the masking state of the thread allows it.

(emphasis not in original). Indeed, the guide recommends explicitly adding interruption points:

Finally, after the interruptible foreign call returns into Haskell, the Haskell code should allow exceptions to be raised [using] Control.Exception’s allowInterrupt (..)

Even that prescription is not enough for the test above, because the SIGPIPE never fires in the first place. SIGPIPE only fires when an exception lands on a thread already in BlockedOnCCall_Interruptible. Here the exception arrived earlier, during c_usleep’s plain BlockedOnCCall, so it was only queued; the RTS doesn’t fire SIGPIPE when the thread later enters the interruptible call. c_pause blocks forever, killThread stays parked, and timeout prints FAIL: killThread hung.

Placing allowInterrupt before the call makes this test pass in practice: the exception queued during c_usleep is raised on the spot, and c_pause never runs. But it does not fix the underlying problem, it merely narrows the gap: an exception that arrives after the allowInterrupt but before the call starts is in exactly the same position as before.

A race in the delivery of cancellation signals

A second, different, kind of race exists between user-space code and the kernel (#27113). Unlike the race from the previous section, this one arises even when exceptions are not masked. Recall the wrapper from earlier:

token = suspendThread(BaseReg, interruptible=True);
r = accept(fd, NULL, NULL);   // libc
BaseReg = resumeThread(token);

The relevant transition happens inside suspendThread. It marks the thread as BlockedOnCCall_Interruptible and then calls releaseCapability. At that point, the rest of the runtime knows that this thread is now in an interruptible foreign call, and any other thread that wants to cancel it can fire SIGPIPE.

But the OS thread executing the wrapper has not entered the syscall yet. After releaseCapability returns, there are still a handful of instructions of bookkeeping, some in the RTS and some in libc itself, and only at the very end does the actual syscall instruction drop into the kernel. All of that happens in user space.

If the cancelling thread fires SIGPIPE during this window, here is what happens:

  1. The kernel delivers SIGPIPE to the OS thread.
  2. The empty handler that GHC installed runs, does nothing, and returns.
  3. The OS thread continues from where it was interrupted, in user space.
  4. Soon after, the thread executes the syscall instruction.
  5. There is no pending signal to abort the syscall, so accept blocks normally, waiting for an incoming connection that may never arrive.

The async exception remains queued, and the OS thread remains blocked in the kernel indefinitely. This is precisely the race we saw in the crash course, except that this time it involves code in the RTS and libc, rather than our own C code.

A careful analysis of where we can place interruption points

Putting these together, with the trailing allowInterrupt recommended by the user’s guide and the leading one from the previous section, gives us the following pattern:

myCall fd = mask_ $ do
  allowInterrupt   -- (1)
  r <- c_call fd   -- interruptible FFI
  allowInterrupt   -- (2)
  return r

For the analysis, let’s assume that c_call eventually enters a blocking kernel syscall which can be interrupted by SIGPIPE.

For each window in which an exception can land we track three outcomes separately: did the syscall actually get interrupted (i.e., did SIGPIPE cause an EINTR return), did the queued Haskell exception ever get raised in user code, and what happens to the result of the call.

Case When the exception arrives Syscall outcome Haskell exception Result of the call
A Before (1) Doesn’t run. Raised by (1). None: the call does not run.
B Between (1) and the foreign call Runs to natural completion. No SIGPIPE is sent: the exception arrived while the thread was in plain Haskell, before BlockedOnCCall_Interruptible, so it was only queued. Sits queued. (2) raises it only if the call ever returns naturally. Lost if the call ever returns: (2) raises the exception.
C In the user-space prologue of the call SIGPIPE is sent but lands between suspendThread and kernel entry, hits the empty handler, and is consumed before the syscall sees it. Runs to natural completion. This is #27113. Same as B: queued, raised by (2) only if the call ever returns. Same as B.
D While the syscall is blocked in the kernel SIGPIPE interrupts; the kernel returns EINTR. Raised by (2). Without (2), returning from an interruptible FFI call is not an interruption point under mask_ and the exception sits queued. None: the syscall was interrupted.
E In the user-space epilogue, or after the call returns and before (2) Already returned. Raised by (2). Lost: (2) raises the exception.
F At (2) or later Already returned. (2) raises it; if later, the next interruption point in caller code does. Lost if (2) raises the exception; otherwise returned to the caller.

With this pattern, cases B and C are the windows where we fail to interrupt the foreign call: B is the gap left by the leading allowInterrupt, and C is the race in the delivery of the SIGPIPE signal.

The pattern is not atomic either. In cases B, C and E the call completes while an exception is pending, and (2) then raises the exception and the result of the call is lost. The polling retry loops in the next section avoid this: they only poll before a call, or after a call that has returned EINTR.

Retrying

A blocking syscall can return EINTR when it is interrupted before completing. This can happen for many reasons, including ordinary process signals and runtime-internal signals such as GHC’s SIGPIPE. With few exceptions (close is one3), a syscall that returns EINTR has had no effect. Such syscalls are atomic in the sense described above, which is what makes it safe to retry them. The GNU C Library manual describes the usual C pattern for interrupted primitives: retry the call on EINTR and propagate other errors.

base provides a combinator for doing exactly this in throwErrnoIfMinus1Retry:

myCall fd = throwErrnoIfMinus1Retry "myCall" $
  c_call fd

When masked

Retrying is the right behaviour when the EINTR was caused by some unrelated signal. If, however, it was caused by an async exception delivered through InterruptibleFFI, we should not retry: we should let the exception unwind the Haskell thread instead. Without a mask, that is exactly what happens: the exception is raised as soon as the call returns, before the loop gets a chance to retry.

Under mask_, on the other hand, returning from an interruptible foreign call is not an interruption point. The exception stays queued, the helper sees EINTR and retries, and the next iteration can then block in the kernel with no further signal to interrupt it. We will call this failure mode D-on-retry.

Polling

One way to avoid D-on-retry is to poll before each attempt:

myCall fd = throwErrnoIfMinus1Retry "myCall" $
  allowInterrupt >> c_call fd

Since throwErrnoIfMinus1Retry retries the whole action, this allowInterrupt runs before the first call and before each retry. If a Haskell exception is pending, it is raised before the wrapper enters C again; otherwise the call proceeds.

If desired, a hand-written loop can instead poll only after the call has returned with EINTR. This is essentially what the GHC user guide recommends:

Finally, after the interruptible foreign call returns into Haskell, the Haskell code should allow exceptions to be raised (Control.Exception’s allowInterrupt, or interruptible yield for non--threaded, see #8684), and implement the EINTR-retrying in Haskell (e.g. using Foreign.C.Error.throwErrnoIfMinus1Retry).

It might look something like this:

myCall fd = fix $ \retry -> c_call fd >>= \case
  -1 -> getErrno >>= \case
    errno | errno == eINTR -> allowInterrupt >> retry
          | otherwise      -> throwErrno "myCall"
  r -> return r

That trailing placement also fixes D-on-retry. It differs from the leading placement above only in the first iteration: it does not poll before the first foreign call, so it does not handle exceptions that were already queued before the wrapper began. That difference can affect exception ordering: the leading version may raise an already queued async exception before a foreign call that would otherwise return a synchronous error.

Neither placement fixes cases B or C. After allowInterrupt returns, the thread is back in masked Haskell code. If an exception arrives before the next c_call enters BlockedOnCCall_Interruptible, it is queued without a SIGPIPE: the next call can then block with no further signal to interrupt it. This is case B again, inside the retry loop. Case C, where SIGPIPE is consumed in the user-space prologue before the syscall begins, is unchanged.

Emulating interruptible operations

In some cases we can run the foreign call under Control.Exception.interruptible; this would get us much closer to what we might have expected from an interruptible foreign call in the first place:

myCall fd = throwErrnoIfMinus1Retry "myCall" $
  interruptible (c_call fd)

interruptible action unmasks for the duration of action if and only if the thread is already in MaskedInterruptible. This is better than using restore or unsafeUnmask:

  • mask $ \restore -> restore c_call unmasks only when the outer caller was already unmasked. Under a masked caller, it is a no-op, so any exceptions arriving before c_call remain queued.
  • unsafeUnmask c_call unmasks unconditionally, including inside uninterruptibleMask_, which violates the caller’s expectation that no exceptions should be delivered under an uninterruptible mask.

Benefits

This is a fundamentally different kind of fix from the allowInterrupt variants above. allowInterrupt polls at a single point: once it returns, the thread is masked again, and an exception that arrives between that point and the moment the RTS marks the thread as BlockedOnCCall_Interruptible is queued without a signal. Moving the poll closer to the call narrows this window, but can never close it. interruptible instead unmasks for an interval that extends right into the foreign call: until the RTS marks the thread as interruptible, an exception is raised directly; from that point on, the RTS sends SIGPIPE.

Case B therefore does not merely become less likely; it disappears altogether. Since the thread is also still unmasked when the call returns, any queued exception is raised before the loop can retry, which takes care of D-on-retry as well. Only the race in case C remains, which is unrelated to masking.

Limitations

Because interruptible unmasks for the whole call, the exception can also be raised after the call has completed, but before control returns to the caller. So interruptible (c_call fd) is not atomic: it can raise an exception after c_call has had its effect. For calls that acquire a resource (a lock, a file descriptor, a child process), this is fatal:

bracket (interruptible c_acquire) c_release use    -- WRONG

The kernel acquires the resource, but the queued exception is raised as interruptible returns. From bracket’s point of view, interruptible c_acquire threw an exception, so it does not register c_release. Thus we leak the resource.

For resource acquisition we must keep the return path masked, and so we have to fall back to polling before each attempt:

acquire = mask_ $ Resource <$>
  throwErrnoIfMinus1Retry "acquire" (allowInterrupt >> c_acquire)

bracket acquire c_release use

This is atomic: an exception can only be raised by allowInterrupt, before c_acquire is called. But falling back to polling means that case B is back: an exception that arrives after allowInterrupt returns but before the RTS marks the thread as interruptible leaves the call hanging indefinitely. Closing that window properly needs support from the RTS; we will come back to this below.

Workarounds

As we have seen, the current implementation of InterruptibleFFI suffers from two race conditions: interruptible foreign calls are not interruptible operations, so an exception that arrives before the thread is marked as interruptible is never acted on (B); and the signal may be sent but lost before the thread enters the kernel (C). B can be avoided in user space, but only at the cost of atomicity; C cannot be avoided in user space at all. In this section we therefore consider a number of workarounds that give us interruptible foreign calls without relying on InterruptibleFFI.

Unfortunately, this is not always possible. Some calls, such as flock (acquiring a file lock) or waitpid (waiting for a child process to terminate), block in the kernel on something we cannot wait for ourselves, and offer no other way to be cancelled: a signal is the only way to interrupt them.4 Calls like these are precisely what InterruptibleFFI was designed for, and we will come back to them when we discuss potential GHC improvements.

Using the IO manager: network

If the foreign call blocks waiting on a file descriptor, we can leave the waiting to GHC’s IO manager instead. A good example of this is the network package. All sockets are kept in non-blocking mode, and blocking operations wait for the socket to become ready using threadWaitRead or threadWaitWrite. The operations themselves are unsafe FFI calls, but they will return immediately, since the socket is in non-blocking mode. Every blocking operation goes through a wrapper:

throwSocketErrorWaitRead :: Socket -> String -> IO a -> IO a
throwSocketErrorWaitRead s name io = withFdSocket s $ \fd ->
    throwSocketErrorIfMinus1RetryMayBlock name
      (threadWaitRead $ fromIntegral fd) io

paired with unsafe foreign imports for the actual syscalls:

foreign import CALLCONV unsafe "accept"
  c_accept  :: CInt -> Ptr sa -> Ptr CInt -> IO CInt
foreign import CALLCONV unsafe "accept4"
  c_accept4 :: CInt -> Ptr sa -> Ptr CInt -> CInt -> IO CInt

A call to accept then proceeds as follows:

  1. The unsafe call runs against a non-blocking fd. If a connection is already pending, it succeeds immediately and the wrapper returns.
  2. Otherwise it returns -1 with errno = EWOULDBLOCK. The wrapper calls threadWaitRead fd.
  3. threadWaitRead registers the fd with the IO Manager and parks the calling thread.
  4. When the kernel signals readiness, the IO Manager wakes the thread and the wrapper retries the unsafe call.

This gives us precisely the semantics we were after. The thread only ever blocks in threadWaitRead, which is a genuine interruptible operation: like takeMVar, it raises any pending exception when it would block, even under mask_, so there is no window B; and since no signals are involved, there is no window C either. The call as a whole is also atomic. threadWaitRead only waits, so if it is interrupted it has had no effect. The call that actually acquires the resource (the accept itself) is a non-blocking unsafe call, and nothing between that call returning and the caller recording its result can raise an exception.

The same recipe applies to any C library that offers a non-blocking interface based on file descriptors: wait for readiness using threadWaitRead or threadWaitWrite, and only then make the call. Calls that block internally, such as getaddrinfo, cannot be cancelled this way: network declares getaddrinfo as safe, so timeout cannot interrupt DNS resolution.

Cooperative cancellation

If the C code can be modified (or already provides some way to cancel it), we can instead run the foreign call as a safe call on a separate thread, and cancel it cooperatively: the calling thread waits for the result in an ordinary interruptible operation, and when it receives an asynchronous exception, it asks the C code to stop through some side channel, waits for the call to return, and re-throws the exception. Using withAsync:

cancellable :: IO () -> IO a -> IO a
cancellable cancel call =
  withAsync call $ \a -> wait a `onException` cancel

Here cancel is the action that asks the C code to stop. withAsync does not let the exception propagate until call has returned, which is important because the C code may still be using memory that the caller is about to free.

Some ways to implement cancel:

  • Write to pipe / eventfd / Windows event. Modify the C function to wait on the cancellation pipe using poll/select in addition to any blocking reads it wants to do.
  • Resource teardown: shutdown(2) on a socket aborts blocked accept/recv/send, close(2) on certain fds wakes blocked readers.
  • Library-specific cancel APIs like SQLite’s sqlite3_interrupt.
  • Set a flag that CPU-bound C code polls during long computations that don’t block on kernel events.

As an example of the first, here is a C function that waits until a file descriptor is readable or the call is cancelled:

int wait_readable(int fd, int cancel_fd)
{
    struct pollfd pfds[2] = {
        { .fd = fd,        .events = POLLIN }, // what we are waiting for
        { .fd = cancel_fd, .events = POLLIN }, // readable once we are cancelled
    };
    if (poll(pfds, 2, -1) < 0)         return -1;
    if (pfds[1].revents) { errno = ECANCELED; return -1; }
    return 0;
}

The Haskell wrapper creates a pipe for each call, and cancels the call by writing to it:

foreign import ccall safe "wait_readable"
  c_wait_readable :: CInt -> CInt -> IO CInt

waitReadable :: Fd -> IO ()
waitReadable (Fd fd) =
  bracket createPipe (\(r, w) -> closeFd r >> closeFd w) $ \(Fd r, w) ->
    cancellable (void (fdWrite w "x")) $
      throwErrnoIfMinus1Retry_ "waitReadable" (c_wait_readable fd r)

The pipe is essentially the interrupted flag from the crash course, done properly: every call gets its own pipe, so there is no global signal handler, and nothing to reset. Because it is a file descriptor, the C code can wait for cancellation at the same time as it waits for its data, which closes the race we saw at the end of the crash course, between checking the flag and blocking in accept. And because the byte stays in the pipe, it does not matter whether the C code has started to wait when cancel runs: there is no window B or C.

(For a single file descriptor like this the IO manager would do just as well, of course; the advantage of the pipe is that the same change works for waits buried anywhere inside C code written in an ordinary blocking style.)

cancellable gives us an interruption point, but the resulting operation is only atomic if call has no effect. The calling thread has to receive the exception in order to find out that it should cancel the call, and by then the call may have completed anyway. In that case, either we lose the result and let the exception propagate, or lose/swallow the exception and return the result. Neither choice is a good one.

We might hope to keep both, by returning the result and throwing the exception again from a new thread, so that it is raised at the next interruption point:

forkIO (throwTo caller e)  -- WRONG

This does not work, because a pending exception can be withdrawn. throwTo blocks until the target has received the exception, and if the throwing thread is itself killed before that happens, the target never receives it. timeout relies on this: when its action returns, it kills the thread that is throwing the Timeout exception, in case that exception is still pending. But once we have received the exception, that thread is done, and the copy we throw from our own thread is not timeout’s to withdraw. If the next interruption point comes after timeout has returned, the Timeout exception is raised there, outside the handler that was meant to catch it.

A call that acquires a resource therefore has to be split into two steps:

  • The wait step blocks until the resource can be acquired, but does not acquire it. It has no effect, and it runs under cancellable.
  • The acquire step acquires the resource without blocking, on the calling thread. If it finds that it would block, we go back to waiting.

This is what network does, with the IO manager doing the wait step, like waitReadable above.

If the C code waits and acquires in a single call, the two steps cannot be separated. The calling thread can then end up with both an exception and a resource, and has to release the resource before re-throwing. To find out whether the call acquired a resource after all, we wait for it once more with waitCatch, which is like wait except that it returns an exception thrown by the call instead of re-throwing it:

cancellableAcquire :: IO () -> (a -> IO ()) -> IO a -> IO a
cancellableAcquire cancel release acquire =
  withAsync acquire $ \a ->
    wait a `onException` do
      cancel
      outcome <- uninterruptibleMask_ (waitCatch a)
      case outcome of
        Left _         -> return ()         -- the call failed or was cancelled
        Right resource -> release resource  -- the call completed anyway

We wait under uninterruptibleMask_, because the resource would be lost if this wait were interrupted as well.

This only helps if the effect of the call can be undone. A lock that was taken can be released again, but data that was read from a socket cannot be put back. For such calls we have to choose between the two properties: we either make the call without cancellable, so that it is atomic but cannot be interrupted, or accept that an interrupted call may have had its effect. Having both needs support from the RTS, and we will come back to this below.

This approach has two other downsides. The foreign call doesn’t run on the caller’s OS thread, so forkOS-bound threads and any caller-set thread local state aren’t preserved across the call. And it requires the threaded RTS: otherwise a safe foreign call blocks all Haskell threads, including the one that would cancel it.

Using pthread_cancel

In general it is impossible to safely interrupt foreign code that is not designed for it. If the C code registers its cleanup with pthread_cleanup_push, we can run it on its own thread with pthread_create and cancel it with pthread_cancel:

void *my_foo(void *arg)
{
    int fd = (int)(intptr_t)arg;
    char *buf = malloc(4096);
    pthread_cleanup_push(free, buf);    // runs if the thread is cancelled
    read(fd, buf, 4096);                // blocks: a cancellation point
    pthread_cleanup_pop(1);             // also free on the normal path
    return NULL;
}

pthread_t *my_foo_start(int fd)
{
    pthread_t *t = malloc(sizeof *t);
    pthread_create(t, NULL, my_foo, (void *)(intptr_t)fd);
    return t;
}

void my_foo_cancel(pthread_t *t) { pthread_cancel(*t); }
void my_foo_join(pthread_t *t)   { pthread_join(*t, NULL); }
myFooCancellable :: CInt -> IO ()
myFooCancellable fd = bracket (my_foo_start fd) free $ \t -> do
  done <- newEmptyMVar
  _ <- forkIO $ do
    my_foo_join t                 -- safe call to pthread_join
    putMVar done ()
  takeMVar done `onException` do
    my_foo_cancel t
    takeMVar done                 -- wait for the cleanup handlers to run

This has several drawbacks:

  • Every call creates a new OS thread. We cannot cancel one of the RTS’s own worker threads, because the Haskell thread making the call would never be resumed.
  • The foreign code does not run on the caller’s OS thread, so bound threads and thread local state are not preserved.
  • Most importantly, the C code has to be written carefully for cancellation. Every resource it holds across a cancellation point needs a cleanup handler registered with pthread_cleanup_push, and the same goes for every library it calls. Most C code is not written this way, and cancelling it leaks memory, resources or locks.

Cancellation also only takes effect at a cancellation point like a blocking read, so it does not help with CPU-bound code.

Potential GHC improvements

We propose three changes to GHC. The first two address the two race conditions directly: repeated signalling fixes C, and making interruptible foreign calls interruptible operations fixes B. The third is an independent improvement, and exposes the cancellation state to C code, so that foreign code can cooperate with cancellation without the need for a separate thread.

Repeat SIGPIPE

The race in case C has a simple fix: keep sending the signal. When a thread running an interruptible foreign call has a pending exception, the RTS should repeatedly signal the thread to interrupt any blocking operation it might be doing. The hope is that the call returns to Haskell, ideally with an EINTR, after which the exception can be raised as usual (or, under a mask, at the next interruption point; more on that below).

We are not the first to need this. Java, Ruby, and Zig also interrupt blocked threads by sending them a signal, and they are subject to the same race. All three solve it by sending the signal again.

How often should the signal be sent? Java sends it every 50ms, and Ruby sends it from its timer thread on every tick. A fixed interval works for them because they interrupt known calls to a small set of operations: when one returns EINTR, the runtime checks whether the thread was cancelled. We are attempting to interrupt arbitrary C code. It might handle EINTR itself (though arguably this is an incorrect usage of interruptible FFI). A loop like while (sleep(n)); restarts its wait every time it is interrupted, and if we sent signals at a fixed interval shorter than n, it would never finish. It might also make several blocking calls before it returns, so we have to keep signalling until it does.

Zig uses an exponential backoff instead. We should do the same, so that the gaps eventually grow long enough to handle any such code which includes sections that themselves retry on EINTR.

Make an interruptible FFI call an interruptible operation

The term “interruptible” is overloaded to mean two related but distinct things.

  1. In ordinary Concurrent Haskell it marks operations that act as interruption points under mask and raise any queued exceptions inline.
  2. In InterruptibleFFI it marks foreign calls the runtime tries to abort via SIGPIPE or CancelSynchronousIo. The call itself is not an interruption point in the usual Concurrent Haskell sense.

This is more than a matter of terminology: the fact that an interruptible foreign call is not an interruption point is what causes the first of our two race conditions (B).

From an audit of Hackage (see appendix) we learn that this is a common failure case. Of the eighteen packages using interruptible we looked at, only three make any attempt at an interruption point, and only process has one before the call, which was added after Mitchell Wrosen ran into this same confusion in 2017. All the other examples rely on the annotation alone, including the file locking code in ghc-internal, lukko. Their authors expected interruptible to mean what it means for takeMVar.

So we propose to make the meanings consistent: entering an interruptible foreign call becomes an interruption point (#27110). If the thread is under mask and has a pending exception, the exception is raised before any C code runs. Unlike user code, the RTS can ensure that there is no gap between checking for a pending exception and marking the thread as interruptible: every exception is either raised on entry to the call or, if it arrives after that point, causes the RTS to send a signal. This avoids the problem with the user-space version (allowInterrupt >> c_call fd, the pattern process uses today), where an exception arriving just after the allowInterrupt still falls into window B. Under uninterruptibleMask, exceptions remain masked, as before.

This comes at a price. takeMVar only raises a pending exception if it would otherwise block, but we cannot know in advance whether a foreign call will block, so an interruptible call has to raise unconditionally. This is relevant for calls that release a resource. ghc-internal unlocks a file through the same interruptible import it uses to lock it:

unlockImpl h = do
  FD{fdFD = fd} <- handleToFd h
  throwErrnoIfMinus1_ "flock" $ c_flock fd #{const LOCK_UN}

If this runs as the release action of a bracket while an exception is pending, the exception is raised on entry and the file is never unlocked. Both lukko and unix-simple declare close as interruptible, and lukko retries it when it returns EINTR, which is wrong for close even today. Neither operation needs to be interrupted, so these imports should be safe. Every user of interruptible would have to be checked for this, but as the audit shows, there are only a few declarations to look at, since usage of this extension seems to be relatively rare.

Returning from the call stays as it is today: it is not an interruption point under mask. This is what keeps the call atomic: an exception is only ever raised on entry, before any C code has run. It also closes the gap we were left with in Limitations: the acquire function no longer needs its allowInterrupt, because the check on entry takes its place, and that check leaves no window B.

Putting the two together

With both proposals in place, consider again the bare retry loop from the section on retrying, with no allowInterrupt anywhere:

myCall fd = throwErrnoIfMinus1Retry "myCall" $
  c_call fd

This loop now behaves as follows:

Case When the exception arrives What happens
A, B Before the thread is marked as interruptible Raised on entry. The call does not run.
C In the user-space prologue of the call The first signal may be lost, but the RTS keeps signalling. Eventually the call returns EINTR, the loop retries, and the exception is raised on entry.
D While the syscall is blocked in the kernel The signal interrupts the syscall. The call returns EINTR, the loop retries, and the exception is raised on entry.
E, F After the call has returned The result is returned, and the exception is raised at the next interruption point.

In cases A to D the exception is raised when the call has had no effect, and in cases E and F the result of the call is returned first. So myCall is an interruption point, and it is atomic. If the exception is withdrawn after the call has been interrupted, the call returns EINTR with no exception pending, and the loop calls it again, as it would after an unrelated signal.

The diagram below traces one of these scenarios in detail: the exception arrives in window C, the first signal is lost in user space, and a second signal then interrupts the syscall.

This bare retry loop is precisely what most of the packages in our audit use, including the file-locking code in ghc-internal and lukko, and unix’s waitpid wrapper: with both proposals in place, all of these would become correct without any changes.

Expose the cancellation state to C

The cooperative cancellation approach we described above avoids signals altogether, but the foreign call has to run on a sibling thread, so forkOS-bound threads and thread local state are not preserved. The call is also only atomic if it has no effect, or if its effect can be undone.

The sibling thread exists only because the Haskell thread making the call is stuck in C, so another thread has to catch the exception and ask the C code to stop. But we do not need this if we implement these mechanisms in the RTS: it already knows when an exception is queued for a thread in a foreign call.

We propose that the RTS exposes this directly to foreign code (#28253):

HsBool            hs_interrupt_pending(void);
HsInterruptHandle hs_interrupt_handle(void);

Like the cancellation pipe, this is the interrupted flag from the crash course done properly (no global signal handler, and nothing to reset), but now without the need for a separate thread. hs_interrupt_pending replaces a flag that CPU-bound code polls, and hs_interrupt_handle replaces the pipe: it returns a file descriptor on POSIX, or an event HANDLE on Windows, that is ready for as long as the calling thread has a pending exception. The call runs on the caller’s own OS thread.

This works for all three kinds of foreign call:

  • safe: the handle becomes ready when an exception is queued for an unmasked thread, and the exception is raised when the call returns.
  • interruptible: behaves like safe, but the handle also becomes ready under mask: with our previous proposal, an interruptible call is an interruptible operation, so a pending exception should be noticed even if the thread is masked. The RTS also still sends signals, so that blocking operations like flock return.
  • unsafe: the call should not block, but a long computation can poll hs_interrupt_pending. hs_interrupt_handle is not available for unsafe calls.

With an interruptible call under mask, the exception stays queued while the call runs, and can still be withdrawn: the RTS makes the handle ready without raising it. If the call completes anyway, it returns its result, and the exception is raised at the next interruption point. A call that waits and acquires in a single step is therefore atomic, which we could not achieve above unless the call could be undone.

Foreign code must not assume that an exception will actually be raised. The exception can be withdrawn after hs_interrupt_pending has returned true or the handle has become ready, just as it can after the RTS has sent a signal. Foreign code should therefore respond as a syscall does to a signal: fail with EINTR, having had no effect. The Haskell code then retries the call as usual; if the exception is still pending it is raised, and if it has been withdrawn the call runs again.

Conclusions

InterruptibleFFI does not work reliably today. If you need to cancel a blocking foreign call, prefer the IO manager or cooperative cancellation where you can. If the call acquires a resource, split it into a step that waits and a step that acquires without blocking, so that an interrupted call has had no effect. Where you must use an interruptible foreign call, run it under Control.Exception.interruptible if it does not acquire any resources; if it does, poll with allowInterrupt before each attempt instead. Even then, a call may occasionally fail to be interrupted: the signal the RTS uses to interrupt it can be lost before the call has actually started to block, and there is nothing user code can do about that.

We propose three changes to GHC:

  • The RTS keeps signalling a thread in an interruptible foreign call for as long as it has a pending exception (#27113).
  • Entering an interruptible foreign call becomes an interruption point (#27110).
  • The RTS exposes hs_interrupt_pending and hs_interrupt_handle, so that foreign code can cooperate with cancellation without a separate thread (#28253).

The first two make InterruptibleFFI reliable. The second does change behaviour that existing libraries may depend on, however: interruptible imports that are used to release resources (such as close, or unlocking a file) would raise a pending exception on entry, and should become safe instead. If you maintain a binding that uses interruptible, we would like to hear from you on the tickets.

The third change is an independent improvement. Signals can only interrupt C code that is blocked in a system call; for other long-running C code, such as CPU-bound computations, cooperative cancellation is the only option. The change we propose makes cooperative cancellation possible without a separate thread, so that bound threads and thread-local state are preserved, and a call that waits and acquires in a single step can be atomic.

Appendix: Impact analysis

In this appendix we look at how widely InterruptibleFFI is used on Hackage, and at how the problems discussed in this post affect the packages that use it.

First, how widely is the extension used, and by whom? We surveyed all 18,958 latest Hackage package versions as of early 2026, scanning the sources for foreign import declarations. The numbers below count native imports only, not Javascript FFI declarations.

By strategy:5

Strategy Imports % of native FFI
safe 74,848 59.5%
unsafe 44,278 35.2%
interruptible 6,208 4.9%
prim 382 0.3%

Only 31 packages contain any native interruptible declaration: 0.16% of all Hackage and 1.8% of the 1,695 packages with any foreign import. Of those 6,208 declarations, 6,143 come from auto-generated bindings (HROOT-*, direct-rocksdb, hgdal, OGDF, stdcxx) that mark every imported function interruptible indiscriminately. Setting these aside, 18 packages remain, with 65 declarations between them:

Package Imports What it wraps
unix-simple 13 various
tdlib 11 td_json_client_receive
uniform-io 11 various
lukko 9 flock, fcntl(F_OFD_SETLKW), Windows LockFileEx
ghc-internal 5 open, flock, fcntl, LockFileEx
process 2 waitForProcess (POSIX and Windows)
termbox-bindings-c 2 tb_peek_event, tb_poll_event
unix 2 waitpid, sem_wait
filelock 1 flock
fsnotify 1 ReadDirectoryChangesW
haskell-src-exts 1 sleep6
honk 1 beep_do
hpio 1 pollSysfs
ngx-export 1 fcntl
quic 1 socket monitoring
secure-memory 1 readline_max
taffybar 1 XGetWindowProperty
Win32-notify 1 ReadDirectoryChangesW
Total 65

process

waitForProcess is the single most depended-on interruptible call on Hackage, used transitively across much of the ecosystem. The foreign import itself is unremarkable:

foreign import ccall interruptible "waitForProcess" -- NB. safe - can block
  c_waitForProcess :: PHANDLE -> Ptr CInt -> IO CInt

But the call site is not:

waitForProcess' :: PHANDLE -> IO ExitCode
waitForProcess' h = alloca $ \pret -> do
  throwErrnoIfMinus1Retry_ "waitForProcess"
    (allowInterrupt >> c_waitForProcess h pret)
  mkExitCode <$> peek pret

The important detail is the leading allowInterrupt >>. It was added by Mitchell Wrosen in 2017 in process#101 after diagnosing the same mismatch in the meaning of “interruptible” discussed above.

This is precisely the leading variant from Polling: it avoids D-on-retry, but it remains subject to B and C.

ghc-internal

ghc-internal has two interruptible FFI sites with different implementations. c_interruptible_open, used for openFile on slow filesystems (NFS, FUSE), inspects the masking state at runtime and combines a safe fallback under MaskedUninterruptible with a trailing allowInterrupt on EINTR:

c_interruptible_open filepath oflags mode =
  getMaskingState >>= \case
    MaskedUninterruptible -> c_safe_open_ filepath oflags mode
    _ -> do
      open_res <- c_interruptible_open_ filepath oflags mode
      when (open_res == -1) $
        if hostIsThreaded then allowInterrupt
                         else interruptible (IO $ \s -> (# yield# s, () #))
      pure open_res

Hangs on B and C. An exception queued before the call enters C produces no SIGPIPE. If the call then blocks, the trailing allowInterrupt is never reached. That trailing poll only helps after EINTR.

The file-locking primitives in GHC.Internal.IO.Handle.Lock are the other interruptible function here: bare interruptible foreign imports inside an EINTR-retry loop, with no allowInterrupt anywhere. The code is identical across all three platform variants (Flock.hsc for BSD flock, LinuxOFD.hsc for fcntl(F_OFD_SETLKW), Windows.hsc for LockFileEx):

foreign import ccall interruptible "flock"
  c_flock :: CInt -> CInt -> IO CInt

lockImpl h ctx mode block = do
  FD{fdFD = fd} <- handleToFd h
  let flags = cmode .|. (if block then 0 else #{const LOCK_NB})
  fix $ \retry -> c_flock fd flags >>= \case
    0 -> return True
    _ -> getErrno >>= \errno -> if
      | not block, errno == eAGAIN || errno == eACCES -> return False
      | errno == eINTR -> retry
      | otherwise -> ioException $ errnoToIOError ctx errno (Just h) Nothing

This is precisely the bare retry loop from Retrying, and so is subject to hangs in cases B, C, and D-on-retry: each subsequent iteration re-enters the call with the original exception still queued, so the second attempt can block with no signal to interrupt it.

This file-locking code is what lukko and filelock copied.

lukko

A close copy of ghc-internal’s file-locking code, so the same analysis applies: hangs on B, C, and D-on-retry.

filelock

A small improvement on ghc-internal’s and lukko’s code: Control.Exception.interruptible yield is inserted between EINTR and the recursive call:

| errno == eINTR -> do
    E.interruptible yield
    flock (Fd fd) exclusive block

Hangs on B and C. The trailing interruptible yield handles D-on-retry.

unix

unix exposes two deliberate interruptible imports. getProcessStatus wraps waitpid with a comment that doubles as documentation of why the extension exists at all:

-- safe/interruptible, because this call might block
foreign import ccall interruptible "waitpid"
  c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid

The other is a sem_wait wrapper used by semaphore-compat-1.0 for GHC’s parallel-build coordination. semaphore-compat-2.0 no longer uses this function, and relies on cooperative cancellation instead; in fact, it was a stress test of cancellation while developing semaphore-compat-2.0 that led to the discovery of many of these issues.

These are also subject to the hangs on B, C, and D-on-retry (see Retrying).

Summary

The full package-level summary is:

Package Wraps Retry on EINTR? Interruption-aware?7 Hangs on
process waitForProcess yes leading allowInterrupt B, C
ghc-internal (open) open no (caller’s job) trailing allowInterrupt B, C
ghc-internal (locks) flock, fcntl(F_OFD_SETLKW), LockFileEx yes none B, C, D-on-retry
lukko flock, fcntl(F_OFD_SETLKW), LockFileEx yes none B, C, D-on-retry
filelock flock yes trailing interruptible yield B, C
unix waitpid, sem_wait yes none B, C, D-on-retry
tdlib td_json_client_* no none B, C, D-delayed8
uniform-io getPort, createFromHandler, etc. no none B, C, D-delayed
unix-simple close, fdatasync, etc. no none B, C, D-delayed
termbox-bindings-c tb_peek_event, tb_poll_event no none B, C, D-delayed
fsnotify ReadDirectoryChangesW (Windows) no none B, C, D-delayed
haskell-src-exts sleep no none B, C, D-delayed
honk beep_do no none B, C, D-delayed
hpio pollSysfs yes none B, C, D-on-retry
ngx-export fcntl(F_SETLKW) no none B, C, D-delayed
quic watch_socket no none B, C, D-delayed
secure-memory readline_max no none B, C, D-delayed
taffybar XGetWindowProperty no none B, C, D-delayed
Win32-notify ReadDirectoryChangesW no none B, C, D-delayed

Three packages use an allowInterrupt-style idiom; none wrap the foreign call itself in Control.Exception.interruptible, and none use mask $ \restore -> .... Of those three, only process puts allowInterrupt before the foreign call, so it covers exceptions that were already queued before entry. ghc-internal and filelock are trailing-only. The other fifteen rely on the interruptible annotation alone.


  1. The default action for SIGPIPE is to terminate the process, but the GHC runtime installs an empty handler for it (#1619). The signal therefore does nothing by itself; its only effect is that a blocking system call in progress when it arrives returns early with EINTR.↩︎

  2. Other ecosystems have similar concepts, such as cancellation safety in Rust and the strong exception guarantee in C++.↩︎

  3. On Linux, close releases the file descriptor even when it returns EINTR. Retrying it is therefore wrong: another thread may have been given the same descriptor in the meantime, and the retry would close that one. See close(2).↩︎

  4. On Linux, pidfd_open provides a file descriptor for a child process, so that waitpid at least can be handled using the IO manager after all; other POSIX platforms have no such facility.↩︎

  5. safe is the default when no annotation is given.↩︎

  6. The lone declaration is in tests/examples/FFIExtensions.hs, a test fixture rather than shipped library API. The audit picks it up because the file lives in the tarball.↩︎

  7. We looked for any use of allowInterrupt (leading, trailing, gated on EINTR), Control.Exception.interruptible applied to the foreign call or to a no-op like yield/return (), mask $ \restore -> restore (...), or unsafeUnmask. Any of these indicates the author was aware of the distinction between an interruptible foreign call and interruptible Concurrent Haskell operations, and made some attempt to give the call takeMVar-style interruption-point semantics. “none” means none of these were present anywhere in the call’s vicinity.↩︎

  8. D-delayed is case D in implementations with no EINTR-retry loop and no allowInterrupt. The SIGPIPE fires, kernel returns EINTR, and the C call returns -1 to Haskell. The exception is parked in blocked_exceptions and is delivered at the caller’s next interruption point, not at the call site itself. Not a hang in the strict sense, but the timing of cancellation is unspecified and depends on whatever the caller does next.↩︎