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