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 STRING(stg_unblockAsync_err_str, "unblockAsyncExceptions#_ret")
54 INFO_TABLE_RET( stg_unblockAsyncExceptionszh_ret, RET_SMALL )
58 StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) &
59 %lobits32(~(TSO_BLOCKEX|TSO_INTERRUPTIBLE));
61 /* Eagerly raise a blocked exception, if there is one */
62 if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
64 * We have to be very careful here, as in killThread#, since
65 * we are about to raise an async exception in the current
66 * thread, which might result in the thread being killed.
69 STK_CHK_GEN( WDS(2), R1_PTR, stg_unblockAsyncExceptionszh_ret_info);
72 Sp(0) = stg_gc_unpt_r1_info;
74 (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
75 CurrentTSO "ptr") [R1];
78 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
79 jump stg_threadFinished;
82 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
83 jump %ENTRY_CODE(Sp(0));
88 the thread might have been removed from the
89 blocked_exception list by someone else in the meantime.
90 Just restore the stack pointer and continue.
97 jump %ENTRY_CODE(Sp(0));
100 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret, RET_SMALL )
102 StgTSO_flags(CurrentTSO) = %lobits32(
103 TO_W_(StgTSO_flags(CurrentTSO)) | TSO_BLOCKEX | TSO_INTERRUPTIBLE);
106 jump %ENTRY_CODE(Sp(0));
109 stg_blockAsyncExceptionszh
111 /* Args: R1 :: IO a */
112 STK_CHK_GEN( WDS(2)/* worst case */, R1_PTR, stg_blockAsyncExceptionszh);
114 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) == 0) {
116 StgTSO_flags(CurrentTSO) = %lobits32(
117 TO_W_(StgTSO_flags(CurrentTSO)) | TSO_BLOCKEX | TSO_INTERRUPTIBLE);
119 /* avoid growing the stack unnecessarily */
120 if (Sp(0) == stg_blockAsyncExceptionszh_ret_info) {
124 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
132 stg_unblockAsyncExceptionszh
136 /* Args: R1 :: IO a */
137 STK_CHK_GEN( WDS(4), R1_PTR, stg_unblockAsyncExceptionszh);
138 /* 4 words: one for the unblock frame, 3 for setting up the
139 * stack to call maybePerformBlockedException() below.
142 /* If exceptions are already unblocked, there's nothing to do */
143 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
145 StgTSO_flags(CurrentTSO) = %lobits32(
146 TO_W_(StgTSO_flags(CurrentTSO)) & ~(TSO_BLOCKEX|TSO_INTERRUPTIBLE));
148 /* avoid growing the stack unnecessarily */
149 if (Sp(0) == stg_unblockAsyncExceptionszh_ret_info) {
153 Sp(0) = stg_blockAsyncExceptionszh_ret_info;
156 /* Eagerly raise a blocked exception, if there is one */
157 if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
159 * We have to be very careful here, as in killThread#, since
160 * we are about to raise an async exception in the current
161 * thread, which might result in the thread being killed.
163 * Now, if we are to raise an exception in the current
164 * thread, there might be an update frame above us on the
165 * stack due to unsafePerformIO. Hence, the stack must
166 * make sense, because it is about to be snapshotted into
170 Sp(2) = stg_ap_v_info;
172 Sp(0) = stg_enter_info;
175 (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr",
176 CurrentTSO "ptr") [R1];
179 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
180 jump stg_threadFinished;
183 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
184 jump %ENTRY_CODE(Sp(0));
187 /* we'll just call R1 directly, below */
198 stg_asyncExceptionsBlockedzh
201 if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
210 /* args: R1 = TSO to kill, R2 = Exception */
219 /* Needs 3 words because throwToSingleThreaded uses some stack */
220 STK_CHK_GEN( WDS(3), R1_PTR & R2_PTR, stg_killThreadzh);
221 /* We call allocate in throwTo(), so better check for GC */
222 MAYBE_GC(R1_PTR & R2_PTR, stg_killThreadzh);
225 * We might have killed ourselves. In which case, better be *very*
226 * careful. If the exception killed us, then return to the scheduler.
227 * If the exception went to a catch frame, we'll just continue from
231 if (StgTSO_what_next(target) == ThreadRelocated::I16) {
232 target = StgTSO__link(target);
235 if (target == CurrentTSO) {
237 * So what should happen if a thread calls "throwTo self" inside
238 * unsafePerformIO, and later the closure is evaluated by another
239 * thread? Presumably it should behave as if throwTo just returned,
240 * and then continue from there. See #3279, #3288. This is what
241 * happens: on resumption, we will just jump to the next frame on
242 * the stack, which is the return point for stg_killThreadzh.
245 /* ToDo: what if the current thread is blocking exceptions? */
246 foreign "C" throwToSingleThreaded(MyCapability() "ptr",
247 target "ptr", exception "ptr")[R1,R2];
248 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
249 jump stg_threadFinished;
252 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
253 jump %ENTRY_CODE(Sp(0));
258 out = Sp - WDS(1); /* ok to re-use stack space here */
260 (msg) = foreign "C" throwTo(MyCapability() "ptr",
263 exception "ptr") [R1,R2];
266 jump %ENTRY_CODE(Sp(0));
268 StgTSO_why_blocked(CurrentTSO) = BlockedOnMsgThrowTo;
269 StgTSO_block_info(CurrentTSO) = msg;
270 // we must block, and unlock the message before returning
271 jump stg_block_throwto;
276 /* -----------------------------------------------------------------------------
278 -------------------------------------------------------------------------- */
282 /* Catch frames are very similar to update frames, but when entering
283 * one we just pop the frame off the stack and perform the correct
284 * kind of return to the activation record underneath us on the stack.
287 INFO_TABLE_RET(stg_catch_frame, CATCH_FRAME,
288 #if defined(PROFILING)
289 W_ unused1, W_ unused2,
291 W_ unused3, P_ unused4)
293 Sp = Sp + SIZEOF_StgCatchFrame;
294 jump %ENTRY_CODE(Sp(SP_OFF));
297 /* -----------------------------------------------------------------------------
298 * The catch infotable
300 * This should be exactly the same as would be generated by this STG code
302 * catch = {x,h} \n {} -> catch#{x,h}
304 * It is used in deleteThread when reverting blackholes.
305 * -------------------------------------------------------------------------- */
307 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
309 R2 = StgClosure_payload(R1,1); /* h */
310 R1 = StgClosure_payload(R1,0); /* x */
316 /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
317 STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, stg_catchzh);
319 /* Set up the catch frame */
320 Sp = Sp - SIZEOF_StgCatchFrame;
321 SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
323 StgCatchFrame_handler(Sp) = R2;
324 StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
325 TICK_CATCHF_PUSHED();
327 /* Apply R1 to the realworld token */
333 /* -----------------------------------------------------------------------------
334 * The raise infotable
336 * This should be exactly the same as would be generated by this STG code
338 * raise = {err} \n {} -> raise#{err}
340 * It is used in stg_raisezh to update thunks on the update list
341 * -------------------------------------------------------------------------- */
343 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
345 R1 = StgThunk_payload(R1,0);
350 no_break_on_exception: W_[1];
353 INFO_TABLE_RET(stg_raise_ret, RET_SMALL, P_ arg1)
357 W_[no_break_on_exception] = 1;
366 /* args : R1 :: Exception */
370 #if defined(PROFILING)
371 /* Debugging tool: on raising an exception, show where we are. */
373 /* ToDo: currently this is a hack. Would be much better if
374 * the info was only displayed for an *uncaught* exception.
376 if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
377 foreign "C" fprintCCS_stderr(W_[CCCS] "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 outer = StgTRecHeader_enclosing_trec(trec);
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 CInt[rts_stop_on_exception] = 0;
439 ("ptr" ioAction) = foreign "C" deRefStablePtr (W_[rts_breakpoint_io_action] "ptr") [];
442 Sp(5) = stg_raise_ret_info;
443 Sp(4) = stg_noforceIO_info; // required for unregisterised
444 Sp(3) = exception; // the AP_STACK
445 Sp(2) = ghczmprim_GHCziBool_True_closure; // dummy breakpoint info
446 Sp(1) = ghczmprim_GHCziBool_True_closure; // True <=> a breakpoint
448 jump RET_LBL(stg_ap_pppv);
452 if (frame_type == STOP_FRAME) {
454 * We've stripped the entire stack, the thread is now dead.
455 * We will leave the stack in a GC'able state, see the stg_stop_thread
456 * entry code in StgStartup.cmm.
458 Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack
459 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
460 Sp(1) = exception; /* save the exception */
461 Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
462 StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
463 SAVE_THREAD_STATE(); /* inline! */
465 jump stg_threadFinished;
468 /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME. Pop everything
469 * down to and including this frame, update Su, push R1, and enter the handler.
471 if (frame_type == CATCH_FRAME) {
472 handler = StgCatchFrame_handler(Sp);
474 handler = StgCatchSTMFrame_handler(Sp);
477 /* Restore the blocked/unblocked state for asynchronous exceptions
478 * at the CATCH_FRAME.
480 * If exceptions were unblocked, arrange that they are unblocked
481 * again after executing the handler by pushing an
482 * unblockAsyncExceptions_ret stack frame.
484 * If we've reached an STM catch frame then roll back the nested
485 * transaction we were using.
489 if (frame_type == CATCH_FRAME) {
490 Sp = Sp + SIZEOF_StgCatchFrame;
491 if (StgCatchFrame_exceptions_blocked(frame) == 0) {
493 Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
497 trec = StgTSO_trec(CurrentTSO);
498 outer = StgTRecHeader_enclosing_trec(trec);
499 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
500 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
501 StgTSO_trec(CurrentTSO) = outer;
502 Sp = Sp + SIZEOF_StgCatchSTMFrame;
505 /* Ensure that async excpetions are blocked when running the handler.
507 StgTSO_flags(CurrentTSO) = %lobits32(
508 TO_W_(StgTSO_flags(CurrentTSO)) | TSO_BLOCKEX | TSO_INTERRUPTIBLE);
510 /* Call the handler, passing the exception value and a realworld
511 * token as arguments.
519 jump RET_LBL(stg_ap_pv);
524 /* Args :: R1 :: Exception */