2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
6 -- Module : GHC.TopHandler
7 -- Copyright : (c) The University of Glasgow, 2001-2002
8 -- License : see libraries/base/LICENSE
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC Extensions)
14 -- Support for catching exceptions raised during top-level computations
15 -- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)
17 -----------------------------------------------------------------------------
20 module GHC.TopHandler (
21 runMainIO, runIO, runIOFastExit, runNonIO,
22 topHandler, topHandlerFastExit,
23 reportStackOverflow, reportError,
26 #include "HsBaseConfig.h"
28 import Control.OldException as Old
30 import Control.Concurrent.MVar
35 import GHC.Conc hiding (throwTo)
39 import {-# SOURCE #-} GHC.Handle
40 import GHC.IOBase hiding (Exception)
43 -- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is
44 -- called in the program). It catches otherwise uncaught exceptions,
45 -- and also flushes stdout\/stderr before exiting.
46 runMainIO :: IO a -> IO a
49 main_thread_id <- myThreadId
50 weak_tid <- mkWeakThreadId main_thread_id
51 install_interrupt_handler $ do
52 m <- deRefWeak weak_tid
55 Just tid -> throwTo tid (AsyncException UserInterrupt)
62 install_interrupt_handler :: IO () -> IO ()
63 #ifdef mingw32_HOST_OS
64 install_interrupt_handler handler = do
65 GHC.ConsoleHandler.installHandler $
75 -- specialised version of System.Posix.Signals.installHandler, which
76 -- isn't available here.
77 install_interrupt_handler handler = do
78 let sig = CONST_SIGINT :: CInt
79 withMVar signalHandlerLock $ \_ ->
81 sptr <- newStablePtr handler
83 stg_sig_install sig STG_SIG_RST p_sp nullPtr
86 foreign import ccall unsafe
89 -> CInt -- action code (STG_SIG_HAN etc.)
90 -> Ptr (StablePtr (IO ())) -- (in, out) Haskell handler
91 -> Ptr () -- (in, out) blocked
92 -> IO CInt -- (ret) action code
95 -- make a weak pointer to a ThreadId: holding the weak pointer doesn't
96 -- keep the thread alive and prevent it from being identified as
97 -- deadlocked. Vitally important for the main thread.
98 mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)
99 mkWeakThreadId t@(ThreadId t#) = IO $ \s ->
100 case mkWeak# t# t (unsafeCoerce# 0#) s of
101 (# s1, w #) -> (# s1, Weak w #)
103 -- | 'runIO' is wrapped around every @foreign export@ and @foreign
104 -- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the
105 -- result of running 'System.Exit.exitWith' in a foreign-exported
106 -- function is the same as in the main thread: it terminates the
109 runIO :: IO a -> IO a
110 runIO main = Old.catch main topHandler
112 -- | Like 'runIO', but in the event of an exception that causes an exit,
113 -- we don't shut down the system cleanly, we just exit. This is
114 -- useful in some cases, because the safe exit version will give other
115 -- threads a chance to clean up first, which might shut down the
116 -- system in a different way. For example, try
118 -- main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000
120 -- This will sometimes exit with "interrupted" and code 0, because the
121 -- main thread is given a chance to shut down when the child thread calls
122 -- safeExit. There is a race to shut down between the main and child threads.
124 runIOFastExit :: IO a -> IO a
125 runIOFastExit main = Old.catch main topHandlerFastExit
126 -- NB. this is used by the testsuite driver
128 -- | The same as 'runIO', but for non-IO computations. Used for
129 -- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these
130 -- are used to export Haskell functions with non-IO types.
132 runNonIO :: a -> IO a
133 runNonIO a = Old.catch (a `seq` return a) topHandler
135 topHandler :: Exception -> IO a
136 topHandler err = Old.catch (real_handler safeExit err) topHandler
138 topHandlerFastExit :: Exception -> IO a
139 topHandlerFastExit err =
140 catchException (real_handler fastExit err) topHandlerFastExit
142 -- Make sure we handle errors while reporting the error!
143 -- (e.g. evaluating the string passed to 'error' might generate
144 -- another error, etc.)
146 real_handler :: (Int -> IO a) -> Exception -> IO a
147 real_handler exit exn =
150 AsyncException StackOverflow -> do
154 AsyncException UserInterrupt -> exitInterrupted
156 -- only the main thread gets ExitException exceptions
157 ExitException ExitSuccess -> exit 0
158 ExitException (ExitFailure n) -> exit n
165 reportStackOverflow :: IO a
166 reportStackOverflow = do callStackOverflowHook; return undefined
168 reportError :: Exception -> IO a
170 handler <- getUncaughtExceptionHandler
174 -- SUP: Are the hooks allowed to re-enter Haskell land? If so, remove
176 foreign import ccall unsafe "stackOverflow"
177 callStackOverflowHook :: IO ()
179 -- try to flush stdout/stderr, but don't worry if we fail
180 -- (these handles might have errors, and we don't want to go into
181 -- an infinite loop).
184 hFlush stdout `catchAny` \_ -> return ()
185 hFlush stderr `catchAny` \_ -> return ()
187 cleanUpAndExit :: Int -> IO a
188 cleanUpAndExit r = do cleanUp; safeExit r
190 -- we have to use unsafeCoerce# to get the 'IO a' result type, since the
191 -- compiler doesn't let us declare that as the result type of a foreign export.
192 safeExit :: Int -> IO a
193 safeExit r = unsafeCoerce# (shutdownHaskellAndExit $ fromIntegral r)
195 exitInterrupted :: IO a
197 #ifdef mingw32_HOST_OS
200 -- we must exit via the default action for SIGINT, so that the
201 -- parent of this process can take appropriate action (see #2301)
202 unsafeCoerce# (shutdownHaskellAndSignal CONST_SIGINT)
204 foreign import ccall "shutdownHaskellAndSignal"
205 shutdownHaskellAndSignal :: CInt -> IO ()
208 -- NOTE: shutdownHaskellAndExit must be called "safe", because it *can*
209 -- re-enter Haskell land through finalizers.
210 foreign import ccall "Rts.h shutdownHaskellAndExit"
211 shutdownHaskellAndExit :: CInt -> IO ()
213 fastExit :: Int -> IO a
214 fastExit r = unsafeCoerce# (stg_exit (fromIntegral r))
216 foreign import ccall "Rts.h stg_exit"
217 stg_exit :: CInt -> IO ()