1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2004
7 * This file is written in a subset of C--, extended with various
8 * features specific to GHC. It is compiled by GHC directly. For the
9 * syntax of .cmm files, see the parser in ghc/compiler/cmm/CmmParse.y.
11 * ---------------------------------------------------------------------------*/
14 #include "RaiseAsync.h"
16 import ghczmprim_GHCziBool_True_closure;
18 /* -----------------------------------------------------------------------------
21 A thread can request that asynchronous exceptions not be delivered
22 ("blocked") for the duration of an I/O computation. The primitive
24 blockAsyncExceptions# :: IO a -> IO a
26 is used for this purpose. During a blocked section, asynchronous
27 exceptions may be unblocked again temporarily:
29 unblockAsyncExceptions# :: IO a -> IO a
31 Furthermore, asynchronous exceptions are blocked automatically during
32 the execution of an exception handler. Both of these primitives
33 leave a continuation on the stack which reverts to the previous
34 state (blocked or unblocked) on exit.
36 A thread which wants to raise an exception in another thread (using
37 killThread#) must block until the target thread is ready to receive
38 it. The action of unblocking exceptions in a thread will release all
39 the threads waiting to deliver exceptions to that thread.
41 NB. there's a bug in here. If a thread is inside an
42 unsafePerformIO, and inside blockAsyncExceptions# (there is an
43 unblockAsyncExceptions_ret on the stack), and it is blocked in an
44 interruptible operation, and it receives an exception, then the
45 unsafePerformIO thunk will be updated with a stack object
46 containing the unblockAsyncExceptions_ret frame. Later, when
47 someone else evaluates this thunk, the blocked exception state is
50 -------------------------------------------------------------------------- */
52 INFO_TABLE_RET( stg_unblockAsyncExceptionszh_ret, RET_SMALL )
56 StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) &
57 ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
59 /* Eagerly raise a blocked exception, if there is one */
60 if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
62 * We have to be very careful here, as in killThread#, since
63 * we are about to raise an async exception in the current
64 * thread, which might result in the thread being killed.
67 STK_CHK_GEN( WDS(2), R1_PTR, stg_unblockAsyncExceptionszh_ret_info);
70 Sp(0) = stg_gc_unpt_r1_info;
72 (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
73 CurrentTSO "ptr") [R1];
76 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
77 jump stg_threadFinished;
80 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
81 jump %ENTRY_CODE(Sp(0));
87 jump %ENTRY_CODE(Sp(0));
90 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret, RET_SMALL )
92 StgTSO_flags(CurrentTSO) =
93 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
96 jump %ENTRY_CODE(Sp(0));
99 blockAsyncExceptionszh_fast
101 /* Args: R1 :: IO a */
102 STK_CHK_GEN( WDS(2)/* worst case */, R1_PTR, blockAsyncExceptionszh_fast);
104 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) == 0) {
106 StgTSO_flags(CurrentTSO) =
107 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
109 /* avoid growing the stack unnecessarily */
110 if (Sp(0) == stg_blockAsyncExceptionszh_ret_info) {
114 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
122 unblockAsyncExceptionszh_fast
126 /* Args: R1 :: IO a */
127 STK_CHK_GEN( WDS(2), R1_PTR, unblockAsyncExceptionszh_fast);
129 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
131 StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) &
132 ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
134 /* Eagerly raise a blocked exception, if there is one */
135 if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
137 * We have to be very careful here, as in killThread#, since
138 * we are about to raise an async exception in the current
139 * thread, which might result in the thread being killed.
142 (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
143 CurrentTSO "ptr") [R1];
146 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
147 jump stg_threadFinished;
150 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
151 jump %ENTRY_CODE(Sp(0));
156 /* avoid growing the stack unnecessarily */
157 if (Sp(0) == stg_unblockAsyncExceptionszh_ret_info) {
161 Sp(0) = stg_blockAsyncExceptionszh_ret_info;
169 asyncExceptionsBlockedzh_fast
172 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
181 /* args: R1 = TSO to kill, R2 = Exception */
190 /* Needs 3 words because throwToSingleThreaded uses some stack */
191 STK_CHK_GEN( WDS(3), R1_PTR & R2_PTR, killThreadzh_fast);
194 * We might have killed ourselves. In which case, better be *very*
195 * careful. If the exception killed us, then return to the scheduler.
196 * If the exception went to a catch frame, we'll just continue from
200 if (StgTSO_what_next(target) == ThreadRelocated::I16) {
201 target = StgTSO__link(target);
204 if (target == CurrentTSO) {
206 /* ToDo: what if the current thread is blocking exceptions? */
207 foreign "C" throwToSingleThreaded(MyCapability() "ptr",
208 target "ptr", exception "ptr")[R1,R2];
209 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
210 jump stg_threadFinished;
213 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
214 jump %ENTRY_CODE(Sp(0));
219 out = Sp - WDS(1); /* ok to re-use stack space here */
221 (retcode) = foreign "C" throwTo(MyCapability() "ptr",
227 switch [THROWTO_SUCCESS .. THROWTO_BLOCKED] (retcode) {
229 case THROWTO_SUCCESS: {
230 jump %ENTRY_CODE(Sp(0));
233 case THROWTO_BLOCKED: {
235 // we must block, and call throwToReleaseTarget() before returning
236 jump stg_block_throwto;
242 /* -----------------------------------------------------------------------------
244 -------------------------------------------------------------------------- */
248 /* Catch frames are very similar to update frames, but when entering
249 * one we just pop the frame off the stack and perform the correct
250 * kind of return to the activation record underneath us on the stack.
253 INFO_TABLE_RET(stg_catch_frame, CATCH_FRAME,
254 #if defined(PROFILING)
255 W_ unused1, W_ unused2,
257 W_ unused3, P_ unused4)
259 Sp = Sp + SIZEOF_StgCatchFrame;
260 jump %ENTRY_CODE(Sp(SP_OFF));
263 /* -----------------------------------------------------------------------------
264 * The catch infotable
266 * This should be exactly the same as would be generated by this STG code
268 * catch = {x,h} \n {} -> catch#{x,h}
270 * It is used in deleteThread when reverting blackholes.
271 * -------------------------------------------------------------------------- */
273 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
275 R2 = StgClosure_payload(R1,1); /* h */
276 R1 = StgClosure_payload(R1,0); /* x */
282 /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
283 STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, catchzh_fast);
285 /* Set up the catch frame */
286 Sp = Sp - SIZEOF_StgCatchFrame;
287 SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
289 StgCatchFrame_handler(Sp) = R2;
290 StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
291 TICK_CATCHF_PUSHED();
293 /* Apply R1 to the realworld token */
299 /* -----------------------------------------------------------------------------
300 * The raise infotable
302 * This should be exactly the same as would be generated by this STG code
304 * raise = {err} \n {} -> raise#{err}
306 * It is used in raisezh_fast to update thunks on the update list
307 * -------------------------------------------------------------------------- */
309 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
311 R1 = StgThunk_payload(R1,0);
316 no_break_on_exception: W_[1];
319 INFO_TABLE_RET(stg_raise_ret, RET_SMALL, P_ arg1)
323 W_[no_break_on_exception] = 1;
332 /* args : R1 :: Exception */
336 #if defined(PROFILING)
337 /* Debugging tool: on raising an exception, show where we are. */
339 /* ToDo: currently this is a hack. Would be much better if
340 * the info was only displayed for an *uncaught* exception.
342 if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
343 foreign "C" fprintCCS_stderr(W_[CCCS] "ptr") [];
348 StgTSO_sp(CurrentTSO) = Sp;
349 (frame_type) = foreign "C" raiseExceptionHelper(BaseReg "ptr", CurrentTSO "ptr", exception "ptr") [];
350 Sp = StgTSO_sp(CurrentTSO);
351 if (frame_type == ATOMICALLY_FRAME) {
352 /* The exception has reached the edge of a memory transaction. Check that
353 * the transaction is valid. If not then perhaps the exception should
354 * not have been thrown: re-run the transaction. "trec" will either be
355 * a top-level transaction running the atomic block, or a nested
356 * transaction running an invariant check. In the latter case we
357 * abort and de-allocate the top-level transaction that encloses it
358 * as well (we could just abandon its transaction record, but this makes
359 * sure it's marked as aborted and available for re-use). */
362 trec = StgTSO_trec(CurrentTSO);
363 (r) = foreign "C" stmValidateNestOfTransactions(trec "ptr") [];
364 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
365 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
366 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
368 if (outer != NO_TREC) {
369 foreign "C" stmAbortTransaction(MyCapability() "ptr", outer "ptr") [];
370 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", outer "ptr") [];
373 StgTSO_trec(CurrentTSO) = NO_TREC;
375 // Transaction was valid: continue searching for a catch frame
376 Sp = Sp + SIZEOF_StgAtomicallyFrame;
377 goto retry_pop_stack;
379 // Transaction was not valid: we retry the exception (otherwise continue
380 // with a further call to raiseExceptionHelper)
381 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
382 StgTSO_trec(CurrentTSO) = trec;
383 R1 = StgAtomicallyFrame_code(Sp);
388 // After stripping the stack, see whether we should break here for
389 // GHCi (c.f. the -fbreak-on-exception flag). We do this after
390 // stripping the stack for a reason: we'll be inspecting values in
391 // GHCi, and it helps if all the thunks under evaluation have
392 // already been updated with the exception, rather than being left
394 if (W_[no_break_on_exception] != 0) {
395 W_[no_break_on_exception] = 0;
397 if (TO_W_(CInt[rts_stop_on_exception]) != 0) {
399 // we don't want any further exceptions to be caught,
400 // until GHCi is ready to handle them. This prevents
401 // deadlock if an exception is raised in InteractiveUI,
402 // for exmplae. Perhaps the stop_on_exception flag should
404 W_[rts_stop_on_exception] = 0;
405 ("ptr" ioAction) = foreign "C" deRefStablePtr (W_[rts_breakpoint_io_action] "ptr") [];
408 Sp(5) = stg_raise_ret_info;
409 Sp(4) = stg_noforceIO_info; // required for unregisterised
410 Sp(3) = exception; // the AP_STACK
411 Sp(2) = ghczmprim_GHCziBool_True_closure; // dummy breakpoint info
412 Sp(1) = ghczmprim_GHCziBool_True_closure; // True <=> a breakpoint
414 jump RET_LBL(stg_ap_pppv);
418 if (frame_type == STOP_FRAME) {
420 * We've stripped the entire stack, the thread is now dead.
421 * We will leave the stack in a GC'able state, see the stg_stop_thread
422 * entry code in StgStartup.cmm.
424 Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack
425 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
426 Sp(1) = exception; /* save the exception */
427 Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
428 StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
429 SAVE_THREAD_STATE(); /* inline! */
431 jump stg_threadFinished;
434 /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME. Pop everything
435 * down to and including this frame, update Su, push R1, and enter the handler.
437 if (frame_type == CATCH_FRAME) {
438 handler = StgCatchFrame_handler(Sp);
440 handler = StgCatchSTMFrame_handler(Sp);
443 /* Restore the blocked/unblocked state for asynchronous exceptions
444 * at the CATCH_FRAME.
446 * If exceptions were unblocked, arrange that they are unblocked
447 * again after executing the handler by pushing an
448 * unblockAsyncExceptions_ret stack frame.
450 * If we've reached an STM catch frame then roll back the nested
451 * transaction we were using.
455 if (frame_type == CATCH_FRAME) {
456 Sp = Sp + SIZEOF_StgCatchFrame;
457 if (StgCatchFrame_exceptions_blocked(frame) == 0) {
459 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
463 trec = StgTSO_trec(CurrentTSO);
464 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
465 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
466 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
467 StgTSO_trec(CurrentTSO) = outer;
468 Sp = Sp + SIZEOF_StgCatchSTMFrame;
471 /* Ensure that async excpetions are blocked when running the handler.
473 StgTSO_flags(CurrentTSO) =
474 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
476 /* Call the handler, passing the exception value and a realworld
477 * token as arguments.
485 jump RET_LBL(stg_ap_pv);
490 /* Args :: R1 :: Exception */