Eagerly raise a blocked exception when entering 'unblock' or exiting 'block'
[ghc-hetmet.git] / rts / Exception.cmm
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2004
4  *
5  * Exception support
6  *
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.
10  *
11  * ---------------------------------------------------------------------------*/
12
13 #include "Cmm.h"
14 #include "RaiseAsync.h"
15
16 /* -----------------------------------------------------------------------------
17    Exception Primitives
18
19    A thread can request that asynchronous exceptions not be delivered
20    ("blocked") for the duration of an I/O computation.  The primitive
21    
22         blockAsyncExceptions# :: IO a -> IO a
23
24    is used for this purpose.  During a blocked section, asynchronous
25    exceptions may be unblocked again temporarily:
26
27         unblockAsyncExceptions# :: IO a -> IO a
28
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.
33
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.
38
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
46    not restored, and the result is that unblockAsyncExceptions_ret
47    will attempt to unblock exceptions in the current thread, but it'll
48    find that the CurrentTSO->blocked_exceptions is NULL.  Hence, we
49    work around this by checking for NULL in awakenBlockedQueue().
50
51    -------------------------------------------------------------------------- */
52
53 INFO_TABLE_RET( stg_unblockAsyncExceptionszh_ret,
54                 0/*framesize*/, 0/*bitmap*/, RET_SMALL )
55 {
56     CInt r;
57
58     // Not true: see comments above
59     // ASSERT(StgTSO_blocked_exceptions(CurrentTSO) != NULL);
60
61     StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) & 
62         ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
63
64     /* Eagerly raise a blocked exception, if there is one */
65     if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
66         /* 
67          * We have to be very careful here, as in killThread#, since
68          * we are about to raise an async exception in the current
69          * thread, which might result in the thread being killed.
70          */
71         SAVE_THREAD_STATE();
72         r = foreign "C" maybePerformBlockedException (MyCapability() "ptr", 
73                                                       CurrentTSO "ptr") [R1];
74
75         if (r != 0::CInt) {
76             if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
77                 R1 = ThreadFinished;
78                 jump StgReturn;
79             } else {
80                 LOAD_THREAD_STATE();
81                 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
82                 jump %ENTRY_CODE(Sp(0));
83             }
84         }
85     }
86
87 #ifdef REG_R1
88     Sp_adj(1);
89     jump %ENTRY_CODE(Sp(0));
90 #else
91     Sp(1) = Sp(0);
92     Sp_adj(1);
93     jump %ENTRY_CODE(Sp(1));
94 #endif
95 }
96
97 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret,
98                 0/*framesize*/, 0/*bitmap*/, RET_SMALL )
99 {
100     // Not true: see comments above
101     // ASSERT(StgTSO_blocked_exceptions(CurrentTSO) == NULL);
102
103     StgTSO_flags(CurrentTSO) = 
104         StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
105
106 #ifdef REG_R1
107     Sp_adj(1);
108     jump %ENTRY_CODE(Sp(0));
109 #else
110     Sp(1) = Sp(0);
111     Sp_adj(1);
112     jump %ENTRY_CODE(Sp(1));
113 #endif
114 }
115
116 blockAsyncExceptionszh_fast
117 {
118     /* Args: R1 :: IO a */
119     STK_CHK_GEN( WDS(2)/* worst case */, R1_PTR, blockAsyncExceptionszh_fast);
120
121     if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) == 0) {
122         
123         StgTSO_flags(CurrentTSO) = 
124            StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
125
126         /* avoid growing the stack unnecessarily */
127         if (Sp(0) == stg_blockAsyncExceptionszh_ret_info) {
128             Sp_adj(1);
129         } else {
130             Sp_adj(-1);
131             Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
132         }
133     }
134     TICK_UNKNOWN_CALL();
135     TICK_SLOW_CALL_v();
136     jump stg_ap_v_fast;
137 }
138
139 unblockAsyncExceptionszh_fast
140 {
141     CInt r;
142
143     /* Args: R1 :: IO a */
144     STK_CHK_GEN( WDS(2), R1_PTR, unblockAsyncExceptionszh_fast);
145
146     if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
147
148         StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) & 
149            ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
150
151         /* Eagerly raise a blocked exception, if there is one */
152         if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
153             /* 
154              * We have to be very careful here, as in killThread#, since
155              * we are about to raise an async exception in the current
156              * thread, which might result in the thread being killed.
157              */
158             SAVE_THREAD_STATE();
159             r = foreign "C" maybePerformBlockedException (MyCapability() "ptr", 
160                                                       CurrentTSO "ptr") [R1];
161
162             if (r != 0::CInt) {
163                 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
164                     R1 = ThreadFinished;
165                     jump StgReturn;
166                 } else {
167                     LOAD_THREAD_STATE();
168                     ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
169                     jump %ENTRY_CODE(Sp(0));
170                 }
171             }
172         }
173
174         /* avoid growing the stack unnecessarily */
175         if (Sp(0) == stg_unblockAsyncExceptionszh_ret_info) {
176             Sp_adj(1);
177         } else {
178             Sp_adj(-1);
179             Sp(0) = stg_blockAsyncExceptionszh_ret_info;
180         }
181     }
182     TICK_UNKNOWN_CALL();
183     TICK_SLOW_CALL_v();
184     jump stg_ap_v_fast;
185 }
186
187
188 killThreadzh_fast
189 {
190     /* args: R1 = TSO to kill, R2 = Exception */
191
192     W_ why_blocked;
193     W_ target;
194     W_ exception;
195     
196     target = R1;
197     exception = R2;
198     
199     STK_CHK_GEN( WDS(3), R1_PTR & R2_PTR, killThreadzh_fast);
200
201     /* 
202      * We might have killed ourselves.  In which case, better be *very*
203      * careful.  If the exception killed us, then return to the scheduler.
204      * If the exception went to a catch frame, we'll just continue from
205      * the handler.
206      */
207     if (target == CurrentTSO) {
208         SAVE_THREAD_STATE();
209         /* ToDo: what if the current thread is blocking exceptions? */
210         foreign "C" throwToSingleThreaded(MyCapability() "ptr", 
211                                           target "ptr", exception "ptr")[R1,R2];
212         if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
213             R1 = ThreadFinished;
214             jump StgReturn;
215         } else {
216             LOAD_THREAD_STATE();
217             ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
218             jump %ENTRY_CODE(Sp(0));
219         }
220     } else {
221         W_ out;
222         W_ retcode;
223         out = BaseReg + OFFSET_StgRegTable_rmp_tmp_w;
224         
225         retcode = foreign "C" throwTo(MyCapability() "ptr",
226                                       CurrentTSO "ptr",
227                                       target "ptr",
228                                       exception "ptr",
229                                       out "ptr") [R1,R2];
230         
231         switch [THROWTO_SUCCESS .. THROWTO_BLOCKED] (retcode) {
232
233         case THROWTO_SUCCESS: {
234             jump %ENTRY_CODE(Sp(0));
235         }
236
237         case THROWTO_BLOCKED: {
238             R3 = W_[out];
239             // we must block, and call throwToReleaseTarget() before returning
240             jump stg_block_throwto;
241         }
242         }
243     }
244 }
245
246 /* -----------------------------------------------------------------------------
247    Catch frames
248    -------------------------------------------------------------------------- */
249
250 #ifdef REG_R1
251 #define CATCH_FRAME_ENTRY_TEMPLATE(label,ret)   \
252    label                                        \
253    {                                            \
254       Sp = Sp + SIZEOF_StgCatchFrame;           \
255       jump ret;                                 \
256    }
257 #else
258 #define CATCH_FRAME_ENTRY_TEMPLATE(label,ret)   \
259    label                                        \
260    {                                            \
261       W_ rval;                                  \
262       rval = Sp(0);                             \
263       Sp = Sp + SIZEOF_StgCatchFrame;           \
264       Sp(0) = rval;                             \
265       jump ret;                                 \
266    }
267 #endif
268
269 #ifdef REG_R1
270 #define SP_OFF 0
271 #else
272 #define SP_OFF 1
273 #endif
274
275 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_0_ret,%RET_VEC(Sp(SP_OFF),0))
276 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_1_ret,%RET_VEC(Sp(SP_OFF),1))
277 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_2_ret,%RET_VEC(Sp(SP_OFF),2))
278 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_3_ret,%RET_VEC(Sp(SP_OFF),3))
279 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_4_ret,%RET_VEC(Sp(SP_OFF),4))
280 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_5_ret,%RET_VEC(Sp(SP_OFF),5))
281 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_6_ret,%RET_VEC(Sp(SP_OFF),6))
282 CATCH_FRAME_ENTRY_TEMPLATE(stg_catch_frame_7_ret,%RET_VEC(Sp(SP_OFF),7))
283
284 #if MAX_VECTORED_RTN > 8
285 #error MAX_VECTORED_RTN has changed: please modify stg_catch_frame too.
286 #endif
287
288 #if defined(PROFILING)
289 #define CATCH_FRAME_BITMAP 7
290 #define CATCH_FRAME_WORDS  4
291 #else
292 #define CATCH_FRAME_BITMAP 1
293 #define CATCH_FRAME_WORDS  2
294 #endif
295
296 /* Catch frames are very similar to update frames, but when entering
297  * one we just pop the frame off the stack and perform the correct
298  * kind of return to the activation record underneath us on the stack.
299  */
300
301 INFO_TABLE_RET(stg_catch_frame,
302                CATCH_FRAME_WORDS, CATCH_FRAME_BITMAP,
303                CATCH_FRAME,
304                stg_catch_frame_0_ret,
305                stg_catch_frame_1_ret,
306                stg_catch_frame_2_ret,
307                stg_catch_frame_3_ret,
308                stg_catch_frame_4_ret,
309                stg_catch_frame_5_ret,
310                stg_catch_frame_6_ret,
311                stg_catch_frame_7_ret)
312 CATCH_FRAME_ENTRY_TEMPLATE(,%ENTRY_CODE(Sp(SP_OFF)))
313
314 /* -----------------------------------------------------------------------------
315  * The catch infotable
316  *
317  * This should be exactly the same as would be generated by this STG code
318  *
319  * catch = {x,h} \n {} -> catch#{x,h}
320  *
321  * It is used in deleteThread when reverting blackholes.
322  * -------------------------------------------------------------------------- */
323
324 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
325 {
326   R2 = StgClosure_payload(R1,1); /* h */
327   R1 = StgClosure_payload(R1,0); /* x */
328   jump catchzh_fast;
329 }
330
331 catchzh_fast
332 {
333     /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
334     STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, catchzh_fast);
335   
336     /* Set up the catch frame */
337     Sp = Sp - SIZEOF_StgCatchFrame;
338     SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
339     
340     StgCatchFrame_handler(Sp) = R2;
341     StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
342     TICK_CATCHF_PUSHED();
343
344     /* Apply R1 to the realworld token */
345     TICK_UNKNOWN_CALL();
346     TICK_SLOW_CALL_v();
347     jump stg_ap_v_fast;
348 }
349
350 /* -----------------------------------------------------------------------------
351  * The raise infotable
352  * 
353  * This should be exactly the same as would be generated by this STG code
354  *
355  *   raise = {err} \n {} -> raise#{err}
356  *
357  * It is used in raisezh_fast to update thunks on the update list
358  * -------------------------------------------------------------------------- */
359
360 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
361 {
362   R1 = StgThunk_payload(R1,0);
363   jump raisezh_fast;
364 }
365
366 raisezh_fast
367 {
368     W_ handler;
369     W_ raise_closure;
370     W_ frame_type;
371     /* args : R1 :: Exception */
372
373
374 #if defined(PROFILING)
375     /* Debugging tool: on raising an  exception, show where we are. */
376
377     /* ToDo: currently this is a hack.  Would be much better if
378      * the info was only displayed for an *uncaught* exception.
379      */
380     if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
381       foreign "C" fprintCCS_stderr(W_[CCCS] "ptr");
382     }
383 #endif
384     
385     /* Inform the Hpc that an exception has been thrown */
386     foreign "C" hs_hpc_event("Raise",CurrentTSO);
387
388 retry_pop_stack:
389     StgTSO_sp(CurrentTSO) = Sp;
390     frame_type = foreign "C" raiseExceptionHelper(BaseReg "ptr", CurrentTSO "ptr", R1 "ptr");
391     Sp = StgTSO_sp(CurrentTSO);
392     if (frame_type == ATOMICALLY_FRAME) {
393       /* The exception has reached the edge of a memory transaction.  Check that 
394        * the transaction is valid.  If not then perhaps the exception should
395        * not have been thrown: re-run the transaction.  "trec" will either be
396        * a top-level transaction running the atomic block, or a nested 
397        * transaction running an invariant check.  In the latter case we
398        * abort and de-allocate the top-level transaction that encloses it
399        * as well (we could just abandon its transaction record, but this makes
400        * sure it's marked as aborted and available for re-use). */
401       W_ trec, outer;
402       W_ r;
403       trec = StgTSO_trec(CurrentTSO);
404       r = foreign "C" stmValidateNestOfTransactions(trec "ptr");
405       "ptr" outer = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
406       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr");
407       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr");
408
409       if (outer != NO_TREC) {
410         foreign "C" stmAbortTransaction(MyCapability() "ptr", outer "ptr");
411         foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", outer "ptr");
412       }
413
414       StgTSO_trec(CurrentTSO) = NO_TREC;
415       if (r != 0) {
416         // Transaction was valid: continue searching for a catch frame
417         Sp = Sp + SIZEOF_StgAtomicallyFrame;
418         goto retry_pop_stack;
419       } else {
420         // Transaction was not valid: we retry the exception (otherwise continue
421         // with a further call to raiseExceptionHelper)
422         "ptr" trec = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr");
423         StgTSO_trec(CurrentTSO) = trec;
424         R1 = StgAtomicallyFrame_code(Sp);
425         jump stg_ap_v_fast;
426       }          
427     }
428
429     if (frame_type == STOP_FRAME) {
430         /*
431          * We've stripped the entire stack, the thread is now dead.
432          * We will leave the stack in a GC'able state, see the stg_stop_thread
433          * entry code in StgStartup.cmm.
434          */
435         Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack 
436                 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
437         Sp(1) = R1;             /* save the exception */
438         Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
439         StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
440         SAVE_THREAD_STATE();    /* inline! */
441
442         /* The return code goes in BaseReg->rRet, and BaseReg is returned in R1 */
443         StgRegTable_rRet(BaseReg) = ThreadFinished;
444         R1 = BaseReg;
445
446         jump StgReturn;
447     }
448
449     /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME.  Pop everything
450      * down to and including this frame, update Su, push R1, and enter the handler.
451      */
452     if (frame_type == CATCH_FRAME) {
453       handler = StgCatchFrame_handler(Sp);
454     } else {
455       handler = StgCatchSTMFrame_handler(Sp);
456     }
457
458     /* Restore the blocked/unblocked state for asynchronous exceptions
459      * at the CATCH_FRAME.  
460      *
461      * If exceptions were unblocked, arrange that they are unblocked
462      * again after executing the handler by pushing an
463      * unblockAsyncExceptions_ret stack frame.
464      *
465      * If we've reached an STM catch frame then roll back the nested
466      * transaction we were using.
467      */
468     W_ frame;
469     frame = Sp;
470     if (frame_type == CATCH_FRAME) {
471       Sp = Sp + SIZEOF_StgCatchFrame;
472       if (StgCatchFrame_exceptions_blocked(frame) == 0) {
473         Sp_adj(-1);
474         Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
475       }
476     } else {
477       W_ trec, outer;
478       trec = StgTSO_trec(CurrentTSO);
479       "ptr" outer = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
480       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
481       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
482       StgTSO_trec(CurrentTSO) = outer;
483       Sp = Sp + SIZEOF_StgCatchSTMFrame;
484     }
485
486     /* Ensure that async excpetions are blocked when running the handler.
487     */
488     StgTSO_flags(CurrentTSO) = 
489         StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
490
491     /* Call the handler, passing the exception value and a realworld
492      * token as arguments.
493      */
494     Sp_adj(-1);
495     Sp(0) = R1;
496     R1 = handler;
497     Sp_adj(-1);
498     TICK_UNKNOWN_CALL();
499     TICK_SLOW_CALL_pv();
500     jump RET_LBL(stg_ap_pv);
501 }
502
503 raiseIOzh_fast
504 {
505   /* Args :: R1 :: Exception */
506   jump raisezh_fast;
507 }