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