8 , ForeignFunctionInterface
11 {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
12 {-# OPTIONS_HADDOCK not-home #-}
14 -----------------------------------------------------------------------------
16 -- Module : GHC.Conc.Sync
17 -- Copyright : (c) The University of Glasgow, 1994-2002
18 -- License : see libraries/base/LICENSE
20 -- Maintainer : cvs-ghc@haskell.org
21 -- Stability : internal
22 -- Portability : non-portable (GHC extensions)
24 -- Basic concurrency stuff.
26 -----------------------------------------------------------------------------
28 -- No: #hide, because bits of this module are exposed by the stm package.
29 -- However, we don't want this module to be the home location for the
30 -- bits it exports, we'd rather have Control.Concurrent and the other
31 -- higher level modules be the home. Hence:
39 -- * Forking and suchlike
40 , forkIO -- :: IO a -> IO ThreadId
42 , forkOnIO -- :: Int -> IO a -> IO ThreadId
44 , numCapabilities -- :: Int
45 , getNumCapabilities -- :: IO Int
46 , numSparks -- :: IO Int
47 , childHandler -- :: Exception -> IO ()
48 , myThreadId -- :: IO ThreadId
49 , killThread -- :: ThreadId -> IO ()
50 , throwTo -- :: ThreadId -> Exception -> IO ()
51 , par -- :: a -> b -> b
52 , pseq -- :: a -> b -> b
55 , labelThread -- :: ThreadId -> String -> IO ()
57 , ThreadStatus(..), BlockReason(..)
58 , threadStatus -- :: ThreadId -> IO ThreadStatus
63 , atomically -- :: STM a -> IO a
65 , orElse -- :: STM a -> STM a -> STM a
66 , throwSTM -- :: Exception e => e -> STM a
67 , catchSTM -- :: Exception e => STM a -> (e -> STM a) -> STM a
68 , alwaysSucceeds -- :: STM a -> STM ()
69 , always -- :: STM Bool -> STM ()
71 , newTVar -- :: a -> STM (TVar a)
72 , newTVarIO -- :: a -> STM (TVar a)
73 , readTVar -- :: TVar a -> STM a
74 , readTVarIO -- :: TVar a -> IO a
75 , writeTVar -- :: a -> TVar a -> STM ()
76 , unsafeIOToSTM -- :: IO a -> STM a
82 , setUncaughtExceptionHandler -- :: (Exception -> IO ()) -> IO ()
83 , getUncaughtExceptionHandler -- :: IO (Exception -> IO ())
85 , reportError, reportStackOverflow
90 import Foreign hiding (unsafePerformIO)
93 #ifdef mingw32_HOST_OS
97 #ifndef mingw32_HOST_OS
104 import {-# SOURCE #-} GHC.IO.Handle ( hFlush )
105 import {-# SOURCE #-} GHC.IO.Handle.FD ( stdout )
107 import GHC.IO.Exception
111 import GHC.Real ( fromIntegral )
112 import GHC.Pack ( packCString# )
113 import GHC.Show ( Show(..), showString )
115 infixr 0 `par`, `pseq`
118 %************************************************************************
120 \subsection{@ThreadId@, @par@, and @fork@}
122 %************************************************************************
125 data ThreadId = ThreadId ThreadId# deriving( Typeable )
126 -- ToDo: data ThreadId = ThreadId (Weak ThreadId#)
127 -- But since ThreadId# is unlifted, the Weak type must use open
130 A 'ThreadId' is an abstract type representing a handle to a thread.
131 'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', where
132 the 'Ord' instance implements an arbitrary total ordering over
133 'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued
134 'ThreadId' to string form; showing a 'ThreadId' value is occasionally
135 useful when debugging or diagnosing the behaviour of a concurrent
138 /Note/: in GHC, if you have a 'ThreadId', you essentially have
139 a pointer to the thread itself. This means the thread itself can\'t be
140 garbage collected until you drop the 'ThreadId'.
141 This misfeature will hopefully be corrected at a later date.
143 /Note/: Hugs does not provide any operations on other threads;
144 it defines 'ThreadId' as a synonym for ().
147 instance Show ThreadId where
149 showString "ThreadId " .
150 showsPrec d (getThreadId (id2TSO t))
152 foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt
154 id2TSO :: ThreadId -> ThreadId#
155 id2TSO (ThreadId t) = t
157 foreign import ccall unsafe "cmp_thread" cmp_thread :: ThreadId# -> ThreadId# -> CInt
160 cmpThread :: ThreadId -> ThreadId -> Ordering
162 case cmp_thread (id2TSO t1) (id2TSO t2) of
167 instance Eq ThreadId where
169 case t1 `cmpThread` t2 of
173 instance Ord ThreadId where
177 Sparks off a new thread to run the 'IO' computation passed as the
178 first argument, and returns the 'ThreadId' of the newly created
181 The new thread will be a lightweight thread; if you want to use a foreign
182 library that uses thread-local storage, use 'Control.Concurrent.forkOS' instead.
184 GHC note: the new thread inherits the /masked/ state of the parent
185 (see 'Control.Exception.mask').
187 The newly created thread has an exception handler that discards the
188 exceptions 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', and
189 'ThreadKilled', and passes all other exceptions to the uncaught
190 exception handler (see 'setUncaughtExceptionHandler').
192 forkIO :: IO () -> IO ThreadId
193 forkIO action = IO $ \ s ->
194 case (fork# action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)
196 action_plus = catchException action childHandler
198 -- | Like 'forkIO', but the child thread is created with asynchronous exceptions
199 -- unmasked (see 'Control.Exception.mask').
200 forkIOUnmasked :: IO () -> IO ThreadId
201 forkIOUnmasked io = forkIO (unsafeUnmask io)
204 Like 'forkIO', but lets you specify on which CPU the thread is
205 created. Unlike a `forkIO` thread, a thread created by `forkOnIO`
206 will stay on the same CPU for its entire lifetime (`forkIO` threads
207 can migrate between CPUs according to the scheduling policy).
208 `forkOnIO` is useful for overriding the scheduling policy when you
209 know in advance how best to distribute the threads.
211 The `Int` argument specifies the CPU number; it is interpreted modulo
212 the value returned by 'getNumCapabilities'.
214 forkOnIO :: Int -> IO () -> IO ThreadId
215 forkOnIO (I# cpu) action = IO $ \ s ->
216 case (forkOn# cpu action_plus s) of (# s1, tid #) -> (# s1, ThreadId tid #)
218 action_plus = catchException action childHandler
220 -- | Like 'forkOnIO', but the child thread is created with
221 -- asynchronous exceptions unmasked (see 'Control.Exception.mask').
222 forkOnIOUnmasked :: Int -> IO () -> IO ThreadId
223 forkOnIOUnmasked cpu io = forkOnIO cpu (unsafeUnmask io)
225 -- | the value passed to the @+RTS -N@ flag. This is the number of
226 -- Haskell threads that can run truly simultaneously at any given
227 -- time, and is typically set to the number of physical CPU cores on
230 -- Strictly speaking it is better to use 'getNumCapabilities', because
231 -- the number of capabilities might vary at runtime.
233 numCapabilities :: Int
234 numCapabilities = unsafePerformIO $ getNumCapabilities
237 Returns the number of Haskell threads that can run truly
238 simultaneously (on separate physical processors) at any given time.
239 The CPU number passed to `forkOnIO` is interpreted modulo this
242 An implementation in which Haskell threads are mapped directly to
243 OS threads might return the number of physical processor cores in
244 the machine, and 'forkOnIO' would be implemented using the OS's
245 affinity facilities. An implementation that schedules Haskell
246 threads onto a smaller number of OS threads (like GHC) would return
247 the number of such OS threads that can be running simultaneously.
249 GHC notes: this returns the number passed as the argument to the
250 @+RTS -N@ flag. In current implementations, the value is fixed
251 when the program starts and never changes, but it is possible that
252 in the future the number of capabilities might vary at runtime.
254 getNumCapabilities :: IO Int
255 getNumCapabilities = do
256 n <- peek n_capabilities
257 return (fromIntegral n)
259 -- | Returns the number of sparks currently in the local spark pool
261 numSparks = IO $ \s -> case numSparks# s of (# s', n #) -> (# s', I# n #)
263 #if defined(mingw32_HOST_OS) && defined(__PIC__)
264 foreign import ccall "_imp__n_capabilities" n_capabilities :: Ptr CInt
266 foreign import ccall "&n_capabilities" n_capabilities :: Ptr CInt
268 childHandler :: SomeException -> IO ()
269 childHandler err = catchException (real_handler err) childHandler
271 real_handler :: SomeException -> IO ()
272 real_handler se@(SomeException ex) =
273 -- ignore thread GC and killThread exceptions:
275 Just BlockedIndefinitelyOnMVar -> return ()
277 Just BlockedIndefinitelyOnSTM -> return ()
279 Just ThreadKilled -> return ()
281 -- report all others:
282 Just StackOverflow -> reportStackOverflow
285 {- | 'killThread' raises the 'ThreadKilled' exception in the given
288 > killThread tid = throwTo tid ThreadKilled
291 killThread :: ThreadId -> IO ()
292 killThread tid = throwTo tid ThreadKilled
294 {- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).
296 'throwTo' does not return until the exception has been raised in the
298 The calling thread can thus be certain that the target
299 thread has received the exception. This is a useful property to know
300 when dealing with race conditions: eg. if there are two threads that
301 can kill each other, it is guaranteed that only one of the threads
302 will get to kill the other.
304 Whatever work the target thread was doing when the exception was
305 raised is not lost: the computation is suspended until required by
308 If the target thread is currently making a foreign call, then the
309 exception will not be raised (and hence 'throwTo' will not return)
310 until the call has completed. This is the case regardless of whether
311 the call is inside a 'mask' or not. However, in GHC a foreign call
312 can be annotated as @interruptible@, in which case a 'throwTo' will
313 cause the RTS to attempt to cause the call to return; see the GHC
314 documentation for more details.
316 Important note: the behaviour of 'throwTo' differs from that described in
317 the paper \"Asynchronous exceptions in Haskell\"
318 (<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).
319 In the paper, 'throwTo' is non-blocking; but the library implementation adopts
320 a more synchronous design in which 'throwTo' does not return until the exception
321 is received by the target thread. The trade-off is discussed in Section 9 of the paper.
322 Like any blocking operation, 'throwTo' is therefore interruptible (see Section 5.3 of
323 the paper). Unlike other interruptible operations, however, 'throwTo'
324 is /always/ interruptible, even if it does not actually block.
326 There is no guarantee that the exception will be delivered promptly,
327 although the runtime will endeavour to ensure that arbitrary
328 delays don't occur. In GHC, an exception can only be raised when a
329 thread reaches a /safe point/, where a safe point is where memory
330 allocation occurs. Some loops do not perform any memory allocation
331 inside the loop and therefore cannot be interrupted by a 'throwTo'.
333 Blocked 'throwTo' is fair: if multiple threads are trying to throw an
334 exception to the same target thread, they will succeed in FIFO order.
337 throwTo :: Exception e => ThreadId -> e -> IO ()
338 throwTo (ThreadId tid) ex = IO $ \ s ->
339 case (killThread# tid (toException ex) s) of s1 -> (# s1, () #)
341 -- | Returns the 'ThreadId' of the calling thread (GHC only).
342 myThreadId :: IO ThreadId
343 myThreadId = IO $ \s ->
344 case (myThreadId# s) of (# s1, tid #) -> (# s1, ThreadId tid #)
347 -- |The 'yield' action allows (forces, in a co-operative multitasking
348 -- implementation) a context-switch to any other currently runnable
349 -- threads (if any), and is occasionally useful when implementing
350 -- concurrency abstractions.
353 case (yield# s) of s1 -> (# s1, () #)
355 {- | 'labelThread' stores a string as identifier for this thread if
356 you built a RTS with debugging support. This identifier will be used in
357 the debugging output to make distinction of different threads easier
358 (otherwise you only have the thread state object\'s address in the heap).
360 Other applications like the graphical Concurrent Haskell Debugger
361 (<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload
362 'labelThread' for their purposes as well.
365 labelThread :: ThreadId -> String -> IO ()
366 labelThread (ThreadId t) str = IO $ \ s ->
367 let !ps = packCString# str
368 !adr = byteArrayContents# ps in
369 case (labelThread# t adr s) of s1 -> (# s1, () #)
371 -- Nota Bene: 'pseq' used to be 'seq'
372 -- but 'seq' is now defined in PrelGHC
374 -- "pseq" is defined a bit weirdly (see below)
376 -- The reason for the strange "lazy" call is that
377 -- it fools the compiler into thinking that pseq and par are non-strict in
378 -- their second argument (even if it inlines pseq at the call site).
379 -- If it thinks pseq is strict in "y", then it often evaluates
380 -- "y" before "x", which is totally wrong.
384 pseq x y = x `seq` lazy y
388 par x y = case (par# x) of { _ -> lazy y }
390 -- | Internal function used by the RTS to run sparks.
393 where loop s = case getSpark# s of
395 if n ==# 0# then (# s', () #)
400 -- ^blocked on on 'MVar'
402 -- ^blocked on a computation in progress by another thread
404 -- ^blocked in 'throwTo'
406 -- ^blocked in 'retry' in an STM transaction
407 | BlockedOnForeignCall
408 -- ^currently in a foreign call
410 -- ^blocked on some other resource. Without @-threaded@,
411 -- I\/O and 'threadDelay' show up as 'BlockedOnOther', with @-threaded@
412 -- they show up as 'BlockedOnMVar'.
413 deriving (Eq,Ord,Show)
415 -- | The current status of a thread
418 -- ^the thread is currently runnable or running
420 -- ^the thread has finished
421 | ThreadBlocked BlockReason
422 -- ^the thread is blocked on some resource
424 -- ^the thread received an uncaught exception
425 deriving (Eq,Ord,Show)
427 threadStatus :: ThreadId -> IO ThreadStatus
428 threadStatus (ThreadId t) = IO $ \s ->
429 case threadStatus# t s of
430 (# s', stat, _cap, _locked #) -> (# s', mk_stat (I# stat) #)
432 -- NB. keep these in sync with includes/Constants.h
433 mk_stat 0 = ThreadRunning
434 mk_stat 1 = ThreadBlocked BlockedOnMVar
435 mk_stat 2 = ThreadBlocked BlockedOnBlackHole
436 mk_stat 6 = ThreadBlocked BlockedOnSTM
437 mk_stat 10 = ThreadBlocked BlockedOnForeignCall
438 mk_stat 11 = ThreadBlocked BlockedOnForeignCall
439 mk_stat 12 = ThreadBlocked BlockedOnException
440 mk_stat 16 = ThreadFinished
441 mk_stat 17 = ThreadDied
442 mk_stat _ = ThreadBlocked BlockedOnOther
444 -- | returns the number of the capability on which the thread is currently
445 -- running, and a boolean indicating whether the thread is locked to
446 -- that capability or not. A thread is locked to a capability if it
447 -- was created with @forkOnIO@.
448 threadCapability :: ThreadId -> IO (Int, Bool)
449 threadCapability (ThreadId t) = IO $ \s ->
450 case threadStatus# t s of
451 (# s', _, cap#, locked# #) -> (# s', (I# cap#, locked# /=# 0#) #)
455 %************************************************************************
457 \subsection[stm]{Transactional heap operations}
459 %************************************************************************
461 TVars are shared memory locations which support atomic memory
465 -- |A monad supporting atomic memory transactions.
466 newtype STM a = STM (State# RealWorld -> (# State# RealWorld, a #))
468 unSTM :: STM a -> (State# RealWorld -> (# State# RealWorld, a #))
471 INSTANCE_TYPEABLE1(STM,stmTc,"STM")
473 instance Functor STM where
474 fmap f x = x >>= (return . f)
476 instance Monad STM where
477 {-# INLINE return #-}
481 return x = returnSTM x
482 m >>= k = bindSTM m k
484 bindSTM :: STM a -> (a -> STM b) -> STM b
485 bindSTM (STM m) k = STM ( \s ->
487 (# new_s, a #) -> unSTM (k a) new_s
490 thenSTM :: STM a -> STM b -> STM b
491 thenSTM (STM m) k = STM ( \s ->
493 (# new_s, _ #) -> unSTM k new_s
496 returnSTM :: a -> STM a
497 returnSTM x = STM (\s -> (# s, x #))
499 instance MonadPlus STM where
503 -- | Unsafely performs IO in the STM monad. Beware: this is a highly
504 -- dangerous thing to do.
506 -- * The STM implementation will often run transactions multiple
507 -- times, so you need to be prepared for this if your IO has any
510 -- * The STM implementation will abort transactions that are known to
511 -- be invalid and need to be restarted. This may happen in the middle
512 -- of `unsafeIOToSTM`, so make sure you don't acquire any resources
513 -- that need releasing (exception handlers are ignored when aborting
514 -- the transaction). That includes doing any IO using Handles, for
515 -- example. Getting this wrong will probably lead to random deadlocks.
517 -- * The transaction may have seen an inconsistent view of memory when
518 -- the IO runs. Invariants that you expect to be true throughout
519 -- your program may not be true inside a transaction, due to the
520 -- way transactions are implemented. Normally this wouldn't be visible
521 -- to the programmer, but using `unsafeIOToSTM` can expose it.
523 unsafeIOToSTM :: IO a -> STM a
524 unsafeIOToSTM (IO m) = STM m
526 -- |Perform a series of STM actions atomically.
528 -- You cannot use 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'.
529 -- Any attempt to do so will result in a runtime error. (Reason: allowing
530 -- this would effectively allow a transaction inside a transaction, depending
531 -- on exactly when the thunk is evaluated.)
533 -- However, see 'newTVarIO', which can be called inside 'unsafePerformIO',
534 -- and which allows top-level TVars to be allocated.
536 atomically :: STM a -> IO a
537 atomically (STM m) = IO (\s -> (atomically# m) s )
539 -- |Retry execution of the current memory transaction because it has seen
540 -- values in TVars which mean that it should not continue (e.g. the TVars
541 -- represent a shared buffer that is now empty). The implementation may
542 -- block the thread until one of the TVars that it has read from has been
543 -- udpated. (GHC only)
545 retry = STM $ \s# -> retry# s#
547 -- |Compose two alternative STM actions (GHC only). If the first action
548 -- completes without retrying then it forms the result of the orElse.
549 -- Otherwise, if the first action retries, then the second action is
550 -- tried in its place. If both actions retry then the orElse as a
552 orElse :: STM a -> STM a -> STM a
553 orElse (STM m) e = STM $ \s -> catchRetry# m (unSTM e) s
555 -- | A variant of 'throw' that can only be used within the 'STM' monad.
557 -- Throwing an exception in @STM@ aborts the transaction and propagates the
560 -- Although 'throwSTM' has a type that is an instance of the type of 'throw', the
561 -- two functions are subtly different:
563 -- > throw e `seq` x ===> throw e
564 -- > throwSTM e `seq` x ===> x
566 -- The first example will cause the exception @e@ to be raised,
567 -- whereas the second one won\'t. In fact, 'throwSTM' will only cause
568 -- an exception to be raised when it is used within the 'STM' monad.
569 -- The 'throwSTM' variant should be used in preference to 'throw' to
570 -- raise an exception within the 'STM' monad because it guarantees
571 -- ordering with respect to other 'STM' operations, whereas 'throw'
573 throwSTM :: Exception e => e -> STM a
574 throwSTM e = STM $ raiseIO# (toException e)
576 -- |Exception handling within STM actions.
577 catchSTM :: Exception e => STM a -> (e -> STM a) -> STM a
578 catchSTM (STM m) handler = STM $ catchSTM# m handler'
580 handler' e = case fromException e of
581 Just e' -> unSTM (handler e')
582 Nothing -> raiseIO# e
584 -- | Low-level primitive on which always and alwaysSucceeds are built.
585 -- checkInv differs form these in that (i) the invariant is not
586 -- checked when checkInv is called, only at the end of this and
587 -- subsequent transcations, (ii) the invariant failure is indicated
588 -- by raising an exception.
589 checkInv :: STM a -> STM ()
590 checkInv (STM m) = STM (\s -> (check# m) s)
592 -- | alwaysSucceeds adds a new invariant that must be true when passed
593 -- to alwaysSucceeds, at the end of the current transaction, and at
594 -- the end of every subsequent transaction. If it fails at any
595 -- of those points then the transaction violating it is aborted
596 -- and the exception raised by the invariant is propagated.
597 alwaysSucceeds :: STM a -> STM ()
598 alwaysSucceeds i = do ( i >> retry ) `orElse` ( return () )
601 -- | always is a variant of alwaysSucceeds in which the invariant is
602 -- expressed as an STM Bool action that must return True. Returning
603 -- False or raising an exception are both treated as invariant failures.
604 always :: STM Bool -> STM ()
605 always i = alwaysSucceeds ( do v <- i
606 if (v) then return () else ( error "Transacional invariant violation" ) )
608 -- |Shared memory locations that support atomic memory transactions.
609 data TVar a = TVar (TVar# RealWorld a)
611 INSTANCE_TYPEABLE1(TVar,tvarTc,"TVar")
613 instance Eq (TVar a) where
614 (TVar tvar1#) == (TVar tvar2#) = sameTVar# tvar1# tvar2#
616 -- |Create a new TVar holding a value supplied
617 newTVar :: a -> STM (TVar a)
618 newTVar val = STM $ \s1# ->
619 case newTVar# val s1# of
620 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
622 -- |@IO@ version of 'newTVar'. This is useful for creating top-level
623 -- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using
624 -- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't
626 newTVarIO :: a -> IO (TVar a)
627 newTVarIO val = IO $ \s1# ->
628 case newTVar# val s1# of
629 (# s2#, tvar# #) -> (# s2#, TVar tvar# #)
631 -- |Return the current value stored in a TVar.
632 -- This is equivalent to
634 -- > readTVarIO = atomically . readTVar
636 -- but works much faster, because it doesn't perform a complete
637 -- transaction, it just reads the current value of the 'TVar'.
638 readTVarIO :: TVar a -> IO a
639 readTVarIO (TVar tvar#) = IO $ \s# -> readTVarIO# tvar# s#
641 -- |Return the current value stored in a TVar
642 readTVar :: TVar a -> STM a
643 readTVar (TVar tvar#) = STM $ \s# -> readTVar# tvar# s#
645 -- |Write the supplied value into a TVar
646 writeTVar :: TVar a -> a -> STM ()
647 writeTVar (TVar tvar#) val = STM $ \s1# ->
648 case writeTVar# tvar# val s1# of
656 withMVar :: MVar a -> (a -> IO b) -> IO b
658 mask $ \restore -> do
660 b <- catchAny (restore (io a))
661 (\e -> do putMVar m a; throw e)
665 modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()
667 mask $ \restore -> do
669 a' <- catchAny (restore (io a))
670 (\e -> do putMVar m a; throw e)
675 %************************************************************************
677 \subsection{Thread waiting}
679 %************************************************************************
683 -- Machinery needed to ensureb that we only have one copy of certain
684 -- CAFs in this module even when the base package is present twice, as
685 -- it is when base is dynamically loaded into GHCi. The RTS keeps
686 -- track of the single true value of the CAF, so even when the CAFs in
687 -- the dynamically-loaded base package are reverted, nothing bad
690 sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a
691 sharedCAF a get_or_set =
693 stable_ref <- newStablePtr a
694 let ref = castPtr (castStablePtrToPtr stable_ref)
695 ref2 <- get_or_set ref
698 else do freeStablePtr stable_ref
699 deRefStablePtr (castPtrToStablePtr (castPtr ref2))
701 reportStackOverflow :: IO ()
702 reportStackOverflow = callStackOverflowHook
704 reportError :: SomeException -> IO ()
706 handler <- getUncaughtExceptionHandler
709 -- SUP: Are the hooks allowed to re-enter Haskell land? If so, remove
711 foreign import ccall unsafe "stackOverflow"
712 callStackOverflowHook :: IO ()
714 {-# NOINLINE uncaughtExceptionHandler #-}
715 uncaughtExceptionHandler :: IORef (SomeException -> IO ())
716 uncaughtExceptionHandler = unsafePerformIO (newIORef defaultHandler)
718 defaultHandler :: SomeException -> IO ()
719 defaultHandler se@(SomeException ex) = do
720 (hFlush stdout) `catchAny` (\ _ -> return ())
721 let msg = case cast ex of
722 Just Deadlock -> "no threads to run: infinite loop or deadlock?"
724 Just (ErrorCall s) -> s
725 _ -> showsPrec 0 se ""
726 withCString "%s" $ \cfmt ->
727 withCString msg $ \cmsg ->
730 -- don't use errorBelch() directly, because we cannot call varargs functions
732 foreign import ccall unsafe "HsBase.h errorBelch2"
733 errorBelch :: CString -> CString -> IO ()
735 setUncaughtExceptionHandler :: (SomeException -> IO ()) -> IO ()
736 setUncaughtExceptionHandler = writeIORef uncaughtExceptionHandler
738 getUncaughtExceptionHandler :: IO (SomeException -> IO ())
739 getUncaughtExceptionHandler = readIORef uncaughtExceptionHandler