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.
69 * raiseAsync assumes that the stack is in ThreadRunGHC state,
70 * i.e. with a return address on the top. In unreg mode, the
71 * return value for IO is on top of the return address, so we
72 * need to make a small adjustment here.
76 STK_CHK_GEN( WDS(2), R1_PTR, stg_unblockAsyncExceptionszh_ret_info);
80 Sp(0) = stg_gc_unpt_r1_info;
82 Sp(0) = stg_ut_1_0_unreg_info;
85 (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
86 CurrentTSO "ptr") [R1];
89 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
90 jump stg_threadFinished;
93 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
94 jump %ENTRY_CODE(Sp(0));
99 * Readjust stack in unregisterised mode if we didn't raise an
100 * exception, see above
110 jump %ENTRY_CODE(Sp(0));
114 jump %ENTRY_CODE(Sp(1));
118 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret, RET_SMALL )
120 StgTSO_flags(CurrentTSO) =
121 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
125 jump %ENTRY_CODE(Sp(0));
129 jump %ENTRY_CODE(Sp(1));
133 blockAsyncExceptionszh_fast
135 /* Args: R1 :: IO a */
136 STK_CHK_GEN( WDS(2)/* worst case */, R1_PTR, blockAsyncExceptionszh_fast);
138 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) == 0) {
140 StgTSO_flags(CurrentTSO) =
141 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
143 /* avoid growing the stack unnecessarily */
144 if (Sp(0) == stg_blockAsyncExceptionszh_ret_info) {
148 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
156 unblockAsyncExceptionszh_fast
160 /* Args: R1 :: IO a */
161 STK_CHK_GEN( WDS(2), R1_PTR, unblockAsyncExceptionszh_fast);
163 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
165 StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) &
166 ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
168 /* Eagerly raise a blocked exception, if there is one */
169 if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
171 * We have to be very careful here, as in killThread#, since
172 * we are about to raise an async exception in the current
173 * thread, which might result in the thread being killed.
176 (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
177 CurrentTSO "ptr") [R1];
180 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
181 jump stg_threadFinished;
184 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
185 jump %ENTRY_CODE(Sp(0));
190 /* avoid growing the stack unnecessarily */
191 if (Sp(0) == stg_unblockAsyncExceptionszh_ret_info) {
195 Sp(0) = stg_blockAsyncExceptionszh_ret_info;
206 /* args: R1 = TSO to kill, R2 = Exception */
215 STK_CHK_GEN( WDS(3), R1_PTR & R2_PTR, killThreadzh_fast);
218 * We might have killed ourselves. In which case, better be *very*
219 * careful. If the exception killed us, then return to the scheduler.
220 * If the exception went to a catch frame, we'll just continue from
224 if (StgTSO_what_next(target) == ThreadRelocated::I16) {
225 target = StgTSO_link(target);
228 if (target == CurrentTSO) {
230 /* ToDo: what if the current thread is blocking exceptions? */
231 foreign "C" throwToSingleThreaded(MyCapability() "ptr",
232 target "ptr", exception "ptr")[R1,R2];
233 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
234 jump stg_threadFinished;
237 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
238 jump %ENTRY_CODE(Sp(0));
243 out = BaseReg + OFFSET_StgRegTable_rmp_tmp_w;
245 (retcode) = foreign "C" throwTo(MyCapability() "ptr",
251 switch [THROWTO_SUCCESS .. THROWTO_BLOCKED] (retcode) {
253 case THROWTO_SUCCESS: {
254 jump %ENTRY_CODE(Sp(0));
257 case THROWTO_BLOCKED: {
259 // we must block, and call throwToReleaseTarget() before returning
260 jump stg_block_throwto;
266 /* -----------------------------------------------------------------------------
268 -------------------------------------------------------------------------- */
276 /* Catch frames are very similar to update frames, but when entering
277 * one we just pop the frame off the stack and perform the correct
278 * kind of return to the activation record underneath us on the stack.
281 INFO_TABLE_RET(stg_catch_frame, CATCH_FRAME,
282 #if defined(PROFILING)
283 W_ unused1, W_ unused2,
285 W_ unused3, "ptr" W_ unused4)
288 Sp = Sp + SIZEOF_StgCatchFrame;
289 jump %ENTRY_CODE(Sp(SP_OFF));
295 Sp = Sp + SIZEOF_StgCatchFrame;
297 jump %ENTRY_CODE(Sp(SP_OFF));
301 /* -----------------------------------------------------------------------------
302 * The catch infotable
304 * This should be exactly the same as would be generated by this STG code
306 * catch = {x,h} \n {} -> catch#{x,h}
308 * It is used in deleteThread when reverting blackholes.
309 * -------------------------------------------------------------------------- */
311 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
313 R2 = StgClosure_payload(R1,1); /* h */
314 R1 = StgClosure_payload(R1,0); /* x */
320 /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
321 STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, catchzh_fast);
323 /* Set up the catch frame */
324 Sp = Sp - SIZEOF_StgCatchFrame;
325 SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
327 StgCatchFrame_handler(Sp) = R2;
328 StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
329 TICK_CATCHF_PUSHED();
331 /* Apply R1 to the realworld token */
337 /* -----------------------------------------------------------------------------
338 * The raise infotable
340 * This should be exactly the same as would be generated by this STG code
342 * raise = {err} \n {} -> raise#{err}
344 * It is used in raisezh_fast to update thunks on the update list
345 * -------------------------------------------------------------------------- */
347 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
349 R1 = StgThunk_payload(R1,0);
354 no_break_on_exception: W_[1];
357 INFO_TABLE_RET(stg_raise_ret, RET_SMALL, "ptr" W_ arg1)
361 W_[no_break_on_exception] = 1;
370 /* args : R1 :: Exception */
374 #if defined(PROFILING)
375 /* Debugging tool: on raising an exception, show where we are. */
377 /* ToDo: currently this is a hack. Would be much better if
378 * the info was only displayed for an *uncaught* exception.
380 if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
381 foreign "C" fprintCCS_stderr(W_[CCCS] "ptr") [];
386 StgTSO_sp(CurrentTSO) = Sp;
387 (frame_type) = foreign "C" raiseExceptionHelper(BaseReg "ptr", CurrentTSO "ptr", exception "ptr") [];
388 Sp = StgTSO_sp(CurrentTSO);
389 if (frame_type == ATOMICALLY_FRAME) {
390 /* The exception has reached the edge of a memory transaction. Check that
391 * the transaction is valid. If not then perhaps the exception should
392 * not have been thrown: re-run the transaction. "trec" will either be
393 * a top-level transaction running the atomic block, or a nested
394 * transaction running an invariant check. In the latter case we
395 * abort and de-allocate the top-level transaction that encloses it
396 * as well (we could just abandon its transaction record, but this makes
397 * sure it's marked as aborted and available for re-use). */
400 trec = StgTSO_trec(CurrentTSO);
401 (r) = foreign "C" stmValidateNestOfTransactions(trec "ptr") [];
402 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
403 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
404 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
406 if (outer != NO_TREC) {
407 foreign "C" stmAbortTransaction(MyCapability() "ptr", outer "ptr") [];
408 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", outer "ptr") [];
411 StgTSO_trec(CurrentTSO) = NO_TREC;
413 // Transaction was valid: continue searching for a catch frame
414 Sp = Sp + SIZEOF_StgAtomicallyFrame;
415 goto retry_pop_stack;
417 // Transaction was not valid: we retry the exception (otherwise continue
418 // with a further call to raiseExceptionHelper)
419 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
420 StgTSO_trec(CurrentTSO) = trec;
421 R1 = StgAtomicallyFrame_code(Sp);
426 // After stripping the stack, see whether we should break here for
427 // GHCi (c.f. the -fbreak-on-exception flag). We do this after
428 // stripping the stack for a reason: we'll be inspecting values in
429 // GHCi, and it helps if all the thunks under evaluation have
430 // already been updated with the exception, rather than being left
432 if (W_[no_break_on_exception] != 0) {
433 W_[no_break_on_exception] = 0;
435 if (TO_W_(CInt[rts_stop_on_exception]) != 0) {
437 // we don't want any further exceptions to be caught,
438 // until GHCi is ready to handle them. This prevents
439 // deadlock if an exception is raised in InteractiveUI,
440 // for exmplae. Perhaps the stop_on_exception flag should
442 W_[rts_stop_on_exception] = 0;
443 ("ptr" ioAction) = foreign "C" deRefStablePtr (W_[rts_breakpoint_io_action] "ptr") [];
446 Sp(5) = stg_raise_ret_info;
447 Sp(4) = stg_noforceIO_info; // required for unregisterised
448 Sp(3) = exception; // the AP_STACK
449 Sp(2) = ghczmprim_GHCziBool_True_closure; // dummy breakpoint info
450 Sp(1) = ghczmprim_GHCziBool_True_closure; // True <=> a breakpoint
452 jump RET_LBL(stg_ap_pppv);
456 if (frame_type == STOP_FRAME) {
458 * We've stripped the entire stack, the thread is now dead.
459 * We will leave the stack in a GC'able state, see the stg_stop_thread
460 * entry code in StgStartup.cmm.
462 Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack
463 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
464 Sp(1) = exception; /* save the exception */
465 Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
466 StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
467 SAVE_THREAD_STATE(); /* inline! */
469 jump stg_threadFinished;
472 /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME. Pop everything
473 * down to and including this frame, update Su, push R1, and enter the handler.
475 if (frame_type == CATCH_FRAME) {
476 handler = StgCatchFrame_handler(Sp);
478 handler = StgCatchSTMFrame_handler(Sp);
481 /* Restore the blocked/unblocked state for asynchronous exceptions
482 * at the CATCH_FRAME.
484 * If exceptions were unblocked, arrange that they are unblocked
485 * again after executing the handler by pushing an
486 * unblockAsyncExceptions_ret stack frame.
488 * If we've reached an STM catch frame then roll back the nested
489 * transaction we were using.
493 if (frame_type == CATCH_FRAME) {
494 Sp = Sp + SIZEOF_StgCatchFrame;
495 if (StgCatchFrame_exceptions_blocked(frame) == 0) {
497 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
501 trec = StgTSO_trec(CurrentTSO);
502 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
503 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
504 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
505 StgTSO_trec(CurrentTSO) = outer;
506 Sp = Sp + SIZEOF_StgCatchSTMFrame;
509 /* Ensure that async excpetions are blocked when running the handler.
511 StgTSO_flags(CurrentTSO) =
512 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
514 /* Call the handler, passing the exception value and a realworld
515 * token as arguments.
523 jump RET_LBL(stg_ap_pv);
528 /* Args :: R1 :: Exception */