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