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 /* -----------------------------------------------------------------------------
19 A thread can request that asynchronous exceptions not be delivered
20 ("blocked") for the duration of an I/O computation. The primitive
22 blockAsyncExceptions# :: IO a -> IO a
24 is used for this purpose. During a blocked section, asynchronous
25 exceptions may be unblocked again temporarily:
27 unblockAsyncExceptions# :: IO a -> IO a
29 Furthermore, asynchronous exceptions are blocked automatically during
30 the execution of an exception handler. Both of these primitives
31 leave a continuation on the stack which reverts to the previous
32 state (blocked or unblocked) on exit.
34 A thread which wants to raise an exception in another thread (using
35 killThread#) must block until the target thread is ready to receive
36 it. The action of unblocking exceptions in a thread will release all
37 the threads waiting to deliver exceptions to that thread.
39 NB. there's a bug in here. If a thread is inside an
40 unsafePerformIO, and inside blockAsyncExceptions# (there is an
41 unblockAsyncExceptions_ret on the stack), and it is blocked in an
42 interruptible operation, and it receives an exception, then the
43 unsafePerformIO thunk will be updated with a stack object
44 containing the unblockAsyncExceptions_ret frame. Later, when
45 someone else evaluates this thunk, the blocked exception state is
48 -------------------------------------------------------------------------- */
50 INFO_TABLE_RET( stg_unblockAsyncExceptionszh_ret,
51 0/*framesize*/, 0/*bitmap*/, RET_SMALL )
55 StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) &
56 ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
58 /* Eagerly raise a blocked exception, if there is one */
59 if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
61 * We have to be very careful here, as in killThread#, since
62 * we are about to raise an async exception in the current
63 * thread, which might result in the thread being killed.
68 * raiseAsync assumes that the stack is in ThreadRunGHC state,
69 * i.e. with a return address on the top. In unreg mode, the
70 * return value for IO is on top of the return address, so we
71 * need to make a small adjustment here.
76 r = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
77 CurrentTSO "ptr") [R1];
80 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
81 jump stg_threadFinished;
84 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
85 jump %ENTRY_CODE(Sp(0));
90 * Readjust stack in unregisterised mode if we didn't raise an
91 * exception, see above
101 jump %ENTRY_CODE(Sp(0));
105 jump %ENTRY_CODE(Sp(1));
109 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret,
110 0/*framesize*/, 0/*bitmap*/, RET_SMALL )
112 StgTSO_flags(CurrentTSO) =
113 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
117 jump %ENTRY_CODE(Sp(0));
121 jump %ENTRY_CODE(Sp(1));
125 blockAsyncExceptionszh_fast
127 /* Args: R1 :: IO a */
128 STK_CHK_GEN( WDS(2)/* worst case */, R1_PTR, blockAsyncExceptionszh_fast);
130 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) == 0) {
132 StgTSO_flags(CurrentTSO) =
133 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
135 /* avoid growing the stack unnecessarily */
136 if (Sp(0) == stg_blockAsyncExceptionszh_ret_info) {
140 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
148 unblockAsyncExceptionszh_fast
152 /* Args: R1 :: IO a */
153 STK_CHK_GEN( WDS(2), R1_PTR, unblockAsyncExceptionszh_fast);
155 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
157 StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) &
158 ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
160 /* Eagerly raise a blocked exception, if there is one */
161 if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
163 * We have to be very careful here, as in killThread#, since
164 * we are about to raise an async exception in the current
165 * thread, which might result in the thread being killed.
168 r = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
169 CurrentTSO "ptr") [R1];
172 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
173 jump stg_threadFinished;
176 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
177 jump %ENTRY_CODE(Sp(0));
182 /* avoid growing the stack unnecessarily */
183 if (Sp(0) == stg_unblockAsyncExceptionszh_ret_info) {
187 Sp(0) = stg_blockAsyncExceptionszh_ret_info;
198 /* args: R1 = TSO to kill, R2 = Exception */
207 STK_CHK_GEN( WDS(3), R1_PTR & R2_PTR, killThreadzh_fast);
210 * We might have killed ourselves. In which case, better be *very*
211 * careful. If the exception killed us, then return to the scheduler.
212 * If the exception went to a catch frame, we'll just continue from
215 if (target == CurrentTSO) {
217 /* ToDo: what if the current thread is blocking exceptions? */
218 foreign "C" throwToSingleThreaded(MyCapability() "ptr",
219 target "ptr", exception "ptr")[R1,R2];
220 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
221 jump stg_threadFinished;
224 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
225 jump %ENTRY_CODE(Sp(0));
230 out = BaseReg + OFFSET_StgRegTable_rmp_tmp_w;
232 retcode = foreign "C" throwTo(MyCapability() "ptr",
238 switch [THROWTO_SUCCESS .. THROWTO_BLOCKED] (retcode) {
240 case THROWTO_SUCCESS: {
241 jump %ENTRY_CODE(Sp(0));
244 case THROWTO_BLOCKED: {
246 // we must block, and call throwToReleaseTarget() before returning
247 jump stg_block_throwto;
253 /* -----------------------------------------------------------------------------
255 -------------------------------------------------------------------------- */
263 #if defined(PROFILING)
264 #define CATCH_FRAME_BITMAP 7
265 #define CATCH_FRAME_WORDS 4
267 #define CATCH_FRAME_BITMAP 1
268 #define CATCH_FRAME_WORDS 2
271 /* Catch frames are very similar to update frames, but when entering
272 * one we just pop the frame off the stack and perform the correct
273 * kind of return to the activation record underneath us on the stack.
276 INFO_TABLE_RET(stg_catch_frame,
277 CATCH_FRAME_WORDS, CATCH_FRAME_BITMAP,
281 Sp = Sp + SIZEOF_StgCatchFrame;
282 jump %ENTRY_CODE(Sp(SP_OFF));
288 Sp = Sp + SIZEOF_StgCatchFrame;
290 jump %ENTRY_CODE(Sp(SP_OFF));
294 /* -----------------------------------------------------------------------------
295 * The catch infotable
297 * This should be exactly the same as would be generated by this STG code
299 * catch = {x,h} \n {} -> catch#{x,h}
301 * It is used in deleteThread when reverting blackholes.
302 * -------------------------------------------------------------------------- */
304 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
306 R2 = StgClosure_payload(R1,1); /* h */
307 R1 = StgClosure_payload(R1,0); /* x */
313 /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
314 STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, catchzh_fast);
316 /* Set up the catch frame */
317 Sp = Sp - SIZEOF_StgCatchFrame;
318 SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
320 StgCatchFrame_handler(Sp) = R2;
321 StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
322 TICK_CATCHF_PUSHED();
324 /* Apply R1 to the realworld token */
330 /* -----------------------------------------------------------------------------
331 * The raise infotable
333 * This should be exactly the same as would be generated by this STG code
335 * raise = {err} \n {} -> raise#{err}
337 * It is used in raisezh_fast to update thunks on the update list
338 * -------------------------------------------------------------------------- */
340 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
342 R1 = StgThunk_payload(R1,0);
347 no_break_on_exception: W_[1];
350 INFO_TABLE_RET(stg_raise_ret, 1, 0, RET_SMALL)
354 W_[no_break_on_exception] = 1;
363 /* args : R1 :: Exception */
367 #if defined(PROFILING)
368 /* Debugging tool: on raising an exception, show where we are. */
370 /* ToDo: currently this is a hack. Would be much better if
371 * the info was only displayed for an *uncaught* exception.
373 if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
374 foreign "C" fprintCCS_stderr(W_[CCCS] "ptr") [];
378 /* Inform the Hpc that an exception has been thrown */
379 foreign "C" hs_hpc_raise_event(CurrentTSO "ptr") [];
382 StgTSO_sp(CurrentTSO) = Sp;
383 frame_type = foreign "C" raiseExceptionHelper(BaseReg "ptr", CurrentTSO "ptr", exception "ptr") [];
384 Sp = StgTSO_sp(CurrentTSO);
385 if (frame_type == ATOMICALLY_FRAME) {
386 /* The exception has reached the edge of a memory transaction. Check that
387 * the transaction is valid. If not then perhaps the exception should
388 * not have been thrown: re-run the transaction. "trec" will either be
389 * a top-level transaction running the atomic block, or a nested
390 * transaction running an invariant check. In the latter case we
391 * abort and de-allocate the top-level transaction that encloses it
392 * as well (we could just abandon its transaction record, but this makes
393 * sure it's marked as aborted and available for re-use). */
396 trec = StgTSO_trec(CurrentTSO);
397 r = foreign "C" stmValidateNestOfTransactions(trec "ptr") [];
398 "ptr" outer = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
399 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
400 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
402 if (outer != NO_TREC) {
403 foreign "C" stmAbortTransaction(MyCapability() "ptr", outer "ptr") [];
404 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", outer "ptr") [];
407 StgTSO_trec(CurrentTSO) = NO_TREC;
409 // Transaction was valid: continue searching for a catch frame
410 Sp = Sp + SIZEOF_StgAtomicallyFrame;
411 goto retry_pop_stack;
413 // Transaction was not valid: we retry the exception (otherwise continue
414 // with a further call to raiseExceptionHelper)
415 "ptr" trec = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
416 StgTSO_trec(CurrentTSO) = trec;
417 R1 = StgAtomicallyFrame_code(Sp);
422 // After stripping the stack, see whether we should break here for
423 // GHCi (c.f. the -fbreak-on-exception flag). We do this after
424 // stripping the stack for a reason: we'll be inspecting values in
425 // GHCi, and it helps if all the thunks under evaluation have
426 // already been updated with the exception, rather than being left
428 if (W_[no_break_on_exception] != 0) {
429 W_[no_break_on_exception] = 0;
431 if (TO_W_(CInt[rts_stop_on_exception]) != 0) {
433 // we don't want any further exceptions to be caught,
434 // until GHCi is ready to handle them. This prevents
435 // deadlock if an exception is raised in InteractiveUI,
436 // for exmplae. Perhaps the stop_on_exception flag should
438 W_[rts_stop_on_exception] = 0;
439 "ptr" ioAction = foreign "C" deRefStablePtr (W_[rts_breakpoint_io_action] "ptr") [];
442 Sp(4) = stg_raise_ret_info;
443 Sp(3) = exception; // the AP_STACK
444 Sp(2) = base_GHCziBase_True_closure; // dummy breakpoint info
445 Sp(1) = base_GHCziBase_True_closure; // True <=> a breakpoint
447 jump stg_ap_pppv_info;
451 if (frame_type == STOP_FRAME) {
453 * We've stripped the entire stack, the thread is now dead.
454 * We will leave the stack in a GC'able state, see the stg_stop_thread
455 * entry code in StgStartup.cmm.
457 Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack
458 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
459 Sp(1) = exception; /* save the exception */
460 Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
461 StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
462 SAVE_THREAD_STATE(); /* inline! */
464 jump stg_threadFinished;
467 /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME. Pop everything
468 * down to and including this frame, update Su, push R1, and enter the handler.
470 if (frame_type == CATCH_FRAME) {
471 handler = StgCatchFrame_handler(Sp);
473 handler = StgCatchSTMFrame_handler(Sp);
476 /* Restore the blocked/unblocked state for asynchronous exceptions
477 * at the CATCH_FRAME.
479 * If exceptions were unblocked, arrange that they are unblocked
480 * again after executing the handler by pushing an
481 * unblockAsyncExceptions_ret stack frame.
483 * If we've reached an STM catch frame then roll back the nested
484 * transaction we were using.
488 if (frame_type == CATCH_FRAME) {
489 Sp = Sp + SIZEOF_StgCatchFrame;
490 if (StgCatchFrame_exceptions_blocked(frame) == 0) {
492 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
496 trec = StgTSO_trec(CurrentTSO);
497 "ptr" outer = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
498 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
499 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
500 StgTSO_trec(CurrentTSO) = outer;
501 Sp = Sp + SIZEOF_StgCatchSTMFrame;
504 /* Ensure that async excpetions are blocked when running the handler.
506 StgTSO_flags(CurrentTSO) =
507 StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
509 /* Call the handler, passing the exception value and a realworld
510 * token as arguments.
518 jump RET_LBL(stg_ap_pv);
523 /* Args :: R1 :: Exception */