2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
5 -- Module : GHC.TopHandler
6 -- Copyright : (c) The University of Glasgow, 2001-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- Support for catching exceptions raised during top-level computations
14 -- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)
16 -----------------------------------------------------------------------------
19 module GHC.TopHandler (
20 runMainIO, runIO, runIOFastExit, runNonIO,
21 topHandler, topHandlerFastExit,
22 reportStackOverflow, reportError,
25 #include "HsBaseConfig.h"
30 import Control.Exception
31 import Control.Concurrent.MVar
40 #ifdef mingw32_HOST_OS
41 import GHC.ConsoleHandler
44 -- | 'runMainIO' is wrapped around 'Main.main' (or whatever main is
45 -- called in the program). It catches otherwise uncaught exceptions,
46 -- and also flushes stdout\/stderr before exiting.
47 runMainIO :: IO a -> IO a
50 main_thread_id <- myThreadId
51 weak_tid <- mkWeakThreadId main_thread_id
52 install_interrupt_handler $ do
53 m <- deRefWeak weak_tid
56 Just tid -> throwTo tid (AsyncException UserInterrupt)
63 install_interrupt_handler :: IO () -> IO ()
64 #ifdef mingw32_HOST_OS
65 install_interrupt_handler handler = do
66 GHC.ConsoleHandler.installHandler $
76 -- specialised version of System.Posix.Signals.installHandler, which
77 -- isn't available here.
78 install_interrupt_handler handler = do
79 let sig = CONST_SIGINT :: CInt
80 withMVar signalHandlerLock $ \_ ->
82 sptr <- newStablePtr handler
84 stg_sig_install sig STG_SIG_RST p_sp nullPtr
87 foreign import ccall unsafe
90 -> CInt -- action code (STG_SIG_HAN etc.)
91 -> Ptr (StablePtr (IO ())) -- (in, out) Haskell handler
92 -> Ptr () -- (in, out) blocked
93 -> IO CInt -- (ret) action code
96 -- make a weak pointer to a ThreadId: holding the weak pointer doesn't
97 -- keep the thread alive and prevent it from being identified as
98 -- deadlocked. Vitally important for the main thread.
99 mkWeakThreadId :: ThreadId -> IO (Weak ThreadId)
100 mkWeakThreadId t@(ThreadId t#) = IO $ \s ->
101 case mkWeak# t# t (unsafeCoerce# 0#) s of
102 (# s1, w #) -> (# s1, Weak w #)
104 -- | 'runIO' is wrapped around every @foreign export@ and @foreign
105 -- import \"wrapper\"@ to mop up any uncaught exceptions. Thus, the
106 -- result of running 'System.Exit.exitWith' in a foreign-exported
107 -- function is the same as in the main thread: it terminates the
110 runIO :: IO a -> IO a
111 runIO main = catchException main topHandler
113 -- | Like 'runIO', but in the event of an exception that causes an exit,
114 -- we don't shut down the system cleanly, we just exit. This is
115 -- useful in some cases, because the safe exit version will give other
116 -- threads a chance to clean up first, which might shut down the
117 -- system in a different way. For example, try
119 -- main = forkIO (runIO (exitWith (ExitFailure 1))) >> threadDelay 10000
121 -- This will sometimes exit with "interrupted" and code 0, because the
122 -- main thread is given a chance to shut down when the child thread calls
123 -- safeExit. There is a race to shut down between the main and child threads.
125 runIOFastExit :: IO a -> IO a
126 runIOFastExit main = catchException main topHandlerFastExit
127 -- NB. this is used by the testsuite driver
129 -- | The same as 'runIO', but for non-IO computations. Used for
130 -- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these
131 -- are used to export Haskell functions with non-IO types.
133 runNonIO :: a -> IO a
134 runNonIO a = catchException (a `seq` return a) topHandler
136 topHandler :: Exception -> IO a
137 topHandler err = catchException (real_handler safeExit err) topHandler
139 topHandlerFastExit :: Exception -> IO a
140 topHandlerFastExit err =
141 catchException (real_handler fastExit err) topHandlerFastExit
143 -- Make sure we handle errors while reporting the error!
144 -- (e.g. evaluating the string passed to 'error' might generate
145 -- another error, etc.)
147 real_handler :: (Int -> IO a) -> Exception -> IO a
148 real_handler exit exn =
151 AsyncException StackOverflow -> do
155 AsyncException UserInterrupt -> exitInterrupted
157 -- only the main thread gets ExitException exceptions
158 ExitException ExitSuccess -> exit 0
159 ExitException (ExitFailure n) -> exit n
166 reportStackOverflow :: IO a
167 reportStackOverflow = do callStackOverflowHook; return undefined
169 reportError :: Exception -> IO a
171 handler <- getUncaughtExceptionHandler
175 -- SUP: Are the hooks allowed to re-enter Haskell land? If so, remove
177 foreign import ccall unsafe "stackOverflow"
178 callStackOverflowHook :: IO ()
180 -- try to flush stdout/stderr, but don't worry if we fail
181 -- (these handles might have errors, and we don't want to go into
182 -- an infinite loop).
185 hFlush stdout `catchException` \_ -> return ()
186 hFlush stderr `catchException` \_ -> return ()
188 cleanUpAndExit :: Int -> IO a
189 cleanUpAndExit r = do cleanUp; safeExit r
191 -- we have to use unsafeCoerce# to get the 'IO a' result type, since the
192 -- compiler doesn't let us declare that as the result type of a foreign export.
193 safeExit :: Int -> IO a
194 safeExit r = unsafeCoerce# (shutdownHaskellAndExit $ fromIntegral r)
196 exitInterrupted :: IO a
198 #ifdef mingw32_HOST_OS
201 -- we must exit via the default action for SIGINT, so that the
202 -- parent of this process can take appropriate action (see #2301)
203 unsafeCoerce# (shutdownHaskellAndSignal CONST_SIGINT)
205 foreign import ccall "shutdownHaskellAndSignal"
206 shutdownHaskellAndSignal :: CInt -> IO ()
209 -- NOTE: shutdownHaskellAndExit must be called "safe", because it *can*
210 -- re-enter Haskell land through finalizers.
211 foreign import ccall "Rts.h shutdownHaskellAndExit"
212 shutdownHaskellAndExit :: CInt -> IO ()
214 fastExit :: Int -> IO a
215 fastExit r = unsafeCoerce# (stg_exit (fromIntegral r))
217 foreign import ccall "Rts.h stg_exit"
218 stg_exit :: CInt -> IO ()