Add explicit imports for RTS-external variables
[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 import base_GHCziBase_True_closure;
17
18 /* -----------------------------------------------------------------------------
19    Exception Primitives
20
21    A thread can request that asynchronous exceptions not be delivered
22    ("blocked") for the duration of an I/O computation.  The primitive
23    
24         blockAsyncExceptions# :: IO a -> IO a
25
26    is used for this purpose.  During a blocked section, asynchronous
27    exceptions may be unblocked again temporarily:
28
29         unblockAsyncExceptions# :: IO a -> IO a
30
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.
35
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.
40
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
48    not restored.
49
50    -------------------------------------------------------------------------- */
51
52 INFO_TABLE_RET( stg_unblockAsyncExceptionszh_ret, RET_SMALL )
53 {
54     CInt r;
55
56     StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) & 
57         ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
58
59     /* Eagerly raise a blocked exception, if there is one */
60     if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
61         /* 
62          * We have to be very careful here, as in killThread#, since
63          * we are about to raise an async exception in the current
64          * thread, which might result in the thread being killed.
65          */
66
67 #ifndef REG_R1
68         /*
69          * raiseAsync assumes that the stack is in ThreadRunGHC state,
70          * i.e. with a return address on the top.  In unreg mode, the
71          * return value for IO is on top of the return address, so we
72          * need to make a small adjustment here.
73          */
74         Sp_adj(1);
75 #endif
76         SAVE_THREAD_STATE();
77         (r) = foreign "C" maybePerformBlockedException (MyCapability() "ptr", 
78                                                       CurrentTSO "ptr") [R1];
79
80         if (r != 0::CInt) {
81             if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
82                 jump stg_threadFinished;
83             } else {
84                 LOAD_THREAD_STATE();
85                 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
86                 jump %ENTRY_CODE(Sp(0));
87             }
88         }
89 #ifndef REG_R1
90         /* 
91          * Readjust stack in unregisterised mode if we didn't raise an
92          * exception, see above
93          */
94         else {
95             Sp_adj(-1);
96         }
97 #endif
98     }
99
100 #ifdef REG_R1
101     Sp_adj(1);
102     jump %ENTRY_CODE(Sp(0));
103 #else
104     Sp(1) = Sp(0);
105     Sp_adj(1);
106     jump %ENTRY_CODE(Sp(1));
107 #endif
108 }
109
110 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret, 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 /* Catch frames are very similar to update frames, but when entering
264  * one we just pop the frame off the stack and perform the correct
265  * kind of return to the activation record underneath us on the stack.
266  */
267
268 INFO_TABLE_RET(stg_catch_frame, CATCH_FRAME,
269 #if defined(PROFILING)
270   W_ unused1, W_ unused2,
271 #endif
272   W_ unused3, "ptr" W_ unused4)
273 #ifdef REG_R1
274    {
275       Sp = Sp + SIZEOF_StgCatchFrame;
276       jump %ENTRY_CODE(Sp(SP_OFF));
277    }
278 #else
279    {
280       W_ rval;
281       rval = Sp(0);
282       Sp = Sp + SIZEOF_StgCatchFrame;
283       Sp(0) = rval;
284       jump %ENTRY_CODE(Sp(SP_OFF));
285    }
286 #endif
287
288 /* -----------------------------------------------------------------------------
289  * The catch infotable
290  *
291  * This should be exactly the same as would be generated by this STG code
292  *
293  * catch = {x,h} \n {} -> catch#{x,h}
294  *
295  * It is used in deleteThread when reverting blackholes.
296  * -------------------------------------------------------------------------- */
297
298 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
299 {
300   R2 = StgClosure_payload(R1,1); /* h */
301   R1 = StgClosure_payload(R1,0); /* x */
302   jump catchzh_fast;
303 }
304
305 catchzh_fast
306 {
307     /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
308     STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, catchzh_fast);
309   
310     /* Set up the catch frame */
311     Sp = Sp - SIZEOF_StgCatchFrame;
312     SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
313     
314     StgCatchFrame_handler(Sp) = R2;
315     StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
316     TICK_CATCHF_PUSHED();
317
318     /* Apply R1 to the realworld token */
319     TICK_UNKNOWN_CALL();
320     TICK_SLOW_CALL_v();
321     jump stg_ap_v_fast;
322 }
323
324 /* -----------------------------------------------------------------------------
325  * The raise infotable
326  * 
327  * This should be exactly the same as would be generated by this STG code
328  *
329  *   raise = {err} \n {} -> raise#{err}
330  *
331  * It is used in raisezh_fast to update thunks on the update list
332  * -------------------------------------------------------------------------- */
333
334 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
335 {
336   R1 = StgThunk_payload(R1,0);
337   jump raisezh_fast;
338 }
339
340 section "data" {
341   no_break_on_exception: W_[1];
342 }
343
344 INFO_TABLE_RET(stg_raise_ret, RET_SMALL, "ptr" W_ arg1)
345 {
346   R1 = Sp(1);
347   Sp = Sp + WDS(2);
348   W_[no_break_on_exception] = 1;  
349   jump raisezh_fast;
350 }
351
352 raisezh_fast
353 {
354     W_ handler;
355     W_ frame_type;
356     W_ exception;
357     /* args : R1 :: Exception */
358
359    exception = R1;
360
361 #if defined(PROFILING)
362     /* Debugging tool: on raising an  exception, show where we are. */
363
364     /* ToDo: currently this is a hack.  Would be much better if
365      * the info was only displayed for an *uncaught* exception.
366      */
367     if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
368       foreign "C" fprintCCS_stderr(W_[CCCS] "ptr") [];
369     }
370 #endif
371     
372 retry_pop_stack:
373     StgTSO_sp(CurrentTSO) = Sp;
374     (frame_type) = foreign "C" raiseExceptionHelper(BaseReg "ptr", CurrentTSO "ptr", exception "ptr") [];
375     Sp = StgTSO_sp(CurrentTSO);
376     if (frame_type == ATOMICALLY_FRAME) {
377       /* The exception has reached the edge of a memory transaction.  Check that 
378        * the transaction is valid.  If not then perhaps the exception should
379        * not have been thrown: re-run the transaction.  "trec" will either be
380        * a top-level transaction running the atomic block, or a nested 
381        * transaction running an invariant check.  In the latter case we
382        * abort and de-allocate the top-level transaction that encloses it
383        * as well (we could just abandon its transaction record, but this makes
384        * sure it's marked as aborted and available for re-use). */
385       W_ trec, outer;
386       W_ r;
387       trec = StgTSO_trec(CurrentTSO);
388       (r) = foreign "C" stmValidateNestOfTransactions(trec "ptr") [];
389       ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
390       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
391       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
392
393       if (outer != NO_TREC) {
394         foreign "C" stmAbortTransaction(MyCapability() "ptr", outer "ptr") [];
395         foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", outer "ptr") [];
396       }
397
398       StgTSO_trec(CurrentTSO) = NO_TREC;
399       if (r != 0) {
400         // Transaction was valid: continue searching for a catch frame
401         Sp = Sp + SIZEOF_StgAtomicallyFrame;
402         goto retry_pop_stack;
403       } else {
404         // Transaction was not valid: we retry the exception (otherwise continue
405         // with a further call to raiseExceptionHelper)
406         ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
407         StgTSO_trec(CurrentTSO) = trec;
408         R1 = StgAtomicallyFrame_code(Sp);
409         jump stg_ap_v_fast;
410       }          
411     }
412
413     // After stripping the stack, see whether we should break here for
414     // GHCi (c.f. the -fbreak-on-exception flag).  We do this after
415     // stripping the stack for a reason: we'll be inspecting values in
416     // GHCi, and it helps if all the thunks under evaluation have
417     // already been updated with the exception, rather than being left
418     // as blackholes.
419     if (W_[no_break_on_exception] != 0) {
420         W_[no_break_on_exception] = 0;
421     } else {
422         if (TO_W_(CInt[rts_stop_on_exception]) != 0) {
423             W_ ioAction;
424             // we don't want any further exceptions to be caught,
425             // until GHCi is ready to handle them.  This prevents
426             // deadlock if an exception is raised in InteractiveUI,
427             // for exmplae.  Perhaps the stop_on_exception flag should
428             // be per-thread.
429             W_[rts_stop_on_exception] = 0;
430             ("ptr" ioAction) = foreign "C" deRefStablePtr (W_[rts_breakpoint_io_action] "ptr") [];
431             Sp = Sp - WDS(6);
432             Sp(5) = exception;
433             Sp(4) = stg_raise_ret_info;
434             Sp(3) = exception;             // the AP_STACK
435             Sp(2) = base_GHCziBase_True_closure; // dummy breakpoint info
436             Sp(1) = base_GHCziBase_True_closure; // True <=> a breakpoint
437             R1 = ioAction;
438             jump stg_ap_pppv_info;
439         }
440     }
441
442     if (frame_type == STOP_FRAME) {
443         /*
444          * We've stripped the entire stack, the thread is now dead.
445          * We will leave the stack in a GC'able state, see the stg_stop_thread
446          * entry code in StgStartup.cmm.
447          */
448         Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack 
449                 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
450         Sp(1) = exception;      /* save the exception */
451         Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
452         StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
453         SAVE_THREAD_STATE();    /* inline! */
454
455         jump stg_threadFinished;
456     }
457
458     /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME.  Pop everything
459      * down to and including this frame, update Su, push R1, and enter the handler.
460      */
461     if (frame_type == CATCH_FRAME) {
462       handler = StgCatchFrame_handler(Sp);
463     } else {
464       handler = StgCatchSTMFrame_handler(Sp);
465     }
466
467     /* Restore the blocked/unblocked state for asynchronous exceptions
468      * at the CATCH_FRAME.  
469      *
470      * If exceptions were unblocked, arrange that they are unblocked
471      * again after executing the handler by pushing an
472      * unblockAsyncExceptions_ret stack frame.
473      *
474      * If we've reached an STM catch frame then roll back the nested
475      * transaction we were using.
476      */
477     W_ frame;
478     frame = Sp;
479     if (frame_type == CATCH_FRAME) {
480       Sp = Sp + SIZEOF_StgCatchFrame;
481       if (StgCatchFrame_exceptions_blocked(frame) == 0) {
482         Sp_adj(-1);
483         Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
484       }
485     } else {
486       W_ trec, outer;
487       trec = StgTSO_trec(CurrentTSO);
488       ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
489       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
490       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
491       StgTSO_trec(CurrentTSO) = outer;
492       Sp = Sp + SIZEOF_StgCatchSTMFrame;
493     }
494
495     /* Ensure that async excpetions are blocked when running the handler.
496     */
497     StgTSO_flags(CurrentTSO) = 
498         StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
499
500     /* Call the handler, passing the exception value and a realworld
501      * token as arguments.
502      */
503     Sp_adj(-1);
504     Sp(0) = exception;
505     R1 = handler;
506     Sp_adj(-1);
507     TICK_UNKNOWN_CALL();
508     TICK_SLOW_CALL_pv();
509     jump RET_LBL(stg_ap_pv);
510 }
511
512 raiseIOzh_fast
513 {
514   /* Args :: R1 :: Exception */
515   jump raisezh_fast;
516 }