2 -----------------------------------------------------------------------------
4 -- Module : GHC.TopHandler
5 -- Copyright : (c) The University of Glasgow, 2001-2002
6 -- License : see libraries/base/LICENSE
8 -- Maintainer : cvs-ghc@haskell.org
9 -- Stability : internal
10 -- Portability : non-portable (GHC Extensions)
12 -- Support for catching exceptions raised during top-level computations
13 -- (e.g. @Main.main@, 'Control.Concurrent.forkIO', and foreign exports)
15 -----------------------------------------------------------------------------
17 module GHC.TopHandler (
18 runIO, runNonIO, reportStackOverflow, reportError
24 import Control.Exception
26 import Foreign.C.String
30 import GHC.Prim (unsafeCoerce#)
32 -- | 'runIO' is wrapped around @Main.main@ by @TcModule@. It is also wrapped
33 -- around every @foreign export@ and @foreign import \"wrapper\"@ to mop up
34 -- any uncaught exceptions. Thus, the result of running
35 -- 'System.Exit.exitWith' in a foreign-exported function is the same as
36 -- in the main thread: it terminates the program.
39 runIO main = catchException main topHandler
41 -- | The same as 'runIO', but for non-IO computations. Used for
42 -- wrapping @foreign export@ and @foreign import \"wrapper\"@ when these
43 -- are used to export Haskell functions with non-IO types.
46 runNonIO a = catchException (a `seq` return a) topHandler
48 topHandler :: Exception -> IO a
49 topHandler err = catchException (real_handler err) topHandler
51 -- Make sure we handle errors while reporting the error!
52 -- (e.g. evaluating the string passed to 'error' might generate
53 -- another error, etc.)
55 real_handler :: Exception -> IO a
58 AsyncException StackOverflow -> reportStackOverflow True
60 -- only the main thread gets ExitException exceptions
61 ExitException ExitSuccess -> safe_exit 0
62 ExitException (ExitFailure n) -> safe_exit n
64 other -> reportError True other
67 reportStackOverflow :: Bool -> IO a
68 reportStackOverflow bombOut = do
69 (hFlush stdout) `catchException` (\ _ -> return ())
75 reportError :: Bool -> Exception -> IO a
76 reportError bombOut ex = do
77 handler <- getUncaughtExceptionHandler
83 -- SUP: Are the hooks allowed to re-enter Haskell land? If so, remove
85 foreign import ccall unsafe "stackOverflow"
86 callStackOverflowHook :: IO ()
88 foreign import ccall unsafe "stg_exit"
89 stg_exit :: Int -> IO ()
92 exit r = unsafeCoerce# (stg_exit r)
94 -- NOTE: shutdownHaskellAndExit must be called "safe", because it *can*
95 -- re-enter Haskell land through finalizers.
96 foreign import ccall "shutdownHaskellAndExit"
97 shutdownHaskellAndExit :: Int -> IO ()
99 -- we have to use unsafeCoerce# to get the 'IO a' result type, since the
100 -- compiler doesn't let us declare that as the result type of a foreign export.
101 safe_exit :: Int -> IO a
102 safe_exit r = unsafeCoerce# (shutdownHaskellAndExit r)