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