--- runMain is applied to Main.main by TcModule
-runMain :: IO a -> IO ()
-runMain main = catchException (main >> return ()) topHandler
-
-topHandler :: Exception -> IO ()
-topHandler err = catchException (real_handler err) topHandler
+-- make a weak pointer to a ThreadId: holding the weak pointer doesn't
+-- keep the thread alive and prevent it from being identified as
+-- deadlocked. Vitally important for the main thread.
+mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)
+mkWeakThreadId t@(ThreadId t#) = IO $ \s ->
+ case mkWeak# t# t (unsafeCoerce# 0#) s of
+ (# s1, w #) -> (# s1, Weak w #)
+
+-- | 'runIO' is wrapped around every @foreign export@ and @foreign
+-- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the
+-- result of running 'System.Exit.exitWith' in a foreign-exported
+-- function is the same as in the main thread: it terminates the
+-- program.
+--
+runIO :: IO a -> IO a
+runIO main = catch main topHandler
+
+-- | Like 'runIO', but in the event of an exception that causes an exit,
+-- we don't shut down the system cleanly, we just exit. This is
+-- useful in some cases, because the safe exit version will give other
+-- threads a chance to clean up first, which might shut down the
+-- system in a different way. For example, try
+--
+-- main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000
+--
+-- This will sometimes exit with "interrupted" and code 0, because the
+-- main thread is given a chance to shut down when the child thread calls
+-- safeExit. There is a race to shut down between the main and child threads.
+--
+runIOFastExit :: IO a -> IO a
+runIOFastExit main = catch main topHandlerFastExit
+ -- NB. this is used by the testsuite driver