ConsoleHandler.c 7.96 KB
Newer Older
sof's avatar
sof committed
1
2
3
4
5
6
7
8
9
10
11
/*
 * Console control handler support.
 *
 */
#include "Rts.h"
#include <windows.h>
#include "ConsoleHandler.h"
#include "SchedAPI.h"
#include "Schedule.h"
#include "RtsUtils.h"
#include "RtsFlags.h"
sof's avatar
sof committed
12
#include "AsyncIO.h"
sof's avatar
sof committed
13
14
15
16
17
18
19
20
21

extern int stg_InstallConsoleEvent(int action, StgStablePtr *handler);

static BOOL WINAPI shutdown_handler(DWORD dwCtrlType);
static BOOL WINAPI generic_handler(DWORD dwCtrlType);

static rtsBool deliver_event = rtsTrue;
static StgInt console_handler = STG_SIG_DFL;

sof's avatar
sof committed
22
23
static HANDLE hConsoleEvent = INVALID_HANDLE_VALUE;

sof's avatar
sof committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#define N_PENDING_EVENTS 16
StgInt stg_pending_events = 0;           /* number of undelivered events */
DWORD stg_pending_buf[N_PENDING_EVENTS]; /* their associated event numbers. */

/*
 * Function: initUserSignals()
 *
 * Initialize the console handling substrate.
 */
void
initUserSignals(void)
{
    stg_pending_events = 0;
    console_handler = STG_SIG_DFL;
sof's avatar
sof committed
38
39
40
    if (hConsoleEvent == INVALID_HANDLE_VALUE) {
	hConsoleEvent = 
	    CreateEvent ( NULL,  /* default security attributes */
sof's avatar
sof committed
41
			  TRUE,  /* manual-reset event */
sof's avatar
sof committed
42
43
44
			  FALSE, /* initially non-signalled */
			  NULL); /* no name */
    }
sof's avatar
sof committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
    return;
}

/*
 * Function: shutdown_handler()
 *
 * Local function that performs the default handling of Ctrl+C kind
 * events; gently shutting down the RTS
 *
 * To repeat Signals.c remark -- user code may choose to override the
 * default handler. Which is fine, assuming they put back the default
 * handler when/if they de-install the custom handler.
 * 
 */
static BOOL WINAPI shutdown_handler(DWORD dwCtrlType)
{
    switch (dwCtrlType) {
    
sof's avatar
sof committed
63
64
65
    case CTRL_CLOSE_EVENT:
	/* see generic_handler() comment re: this event */
	return FALSE;
sof's avatar
sof committed
66
67
68
69
70
71
72
73
74
75
    case CTRL_C_EVENT:
    case CTRL_BREAK_EVENT:

	// If we're already trying to interrupt the RTS, terminate with
	// extreme prejudice.  So the first ^C tries to exit the program
	// cleanly, and the second one just kills it.
	if (interrupted) {
	    stg_exit(EXIT_INTERRUPTED);
	} else {
	    interruptStgRts();
sof's avatar
sof committed
76
77
78
	    /* Cheesy pulsing of an event to wake up a waiting RTS thread, if any */
	    abandonRequestWait();
	    resetAbandonRequestWait();
sof's avatar
sof committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
	}
	return TRUE;

	/* shutdown + logoff events are not handled here. */
    default:
	return FALSE;
    }
}


/*
 * Function: initDefaultHandlers()
 *
 * Install any default signal/console handlers. Currently we install a
 * Ctrl+C handler that shuts down the RTS in an orderly manner.
 */
void initDefaultHandlers(void)
{
    if ( !SetConsoleCtrlHandler(shutdown_handler, TRUE) ) {
98
	errorBelch("warning: failed to install default console handler");
sof's avatar
sof committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    }
}


/*
 * Function: blockUserSignals()
 *
 * Temporarily block the delivery of further console events. Needed to
 * avoid race conditions when GCing the stack of outstanding handlers or
 * when emptying the stack by running the handlers.
 * 
 */
void
blockUserSignals(void)
{
    deliver_event = rtsFalse;
}


/*
 * Function: unblockUserSignals()
 *
 * The inverse of blockUserSignals(); re-enable the deliver of console events.
 */
void
unblockUserSignals(void)
{
    deliver_event = rtsTrue;
}


/*
 * Function: awaitUserSignals()
 *
 * Wait for the next console event. Currently a NOP (returns immediately.)
 */
void awaitUserSignals(void)
{
    return;
}


/*
 * Function: startSignalHandlers()
 *
 * Run the handlers associated with the stacked up console events. Console
 * event delivery is blocked for the duration of this call.
 */
void startSignalHandlers(void)
{
    StgStablePtr handler;

    if (console_handler < 0) {
	return;
    }
    blockUserSignals();
    
    handler = deRefStablePtr((StgStablePtr)console_handler);
    while (stg_pending_events > 0) {
	stg_pending_events--;
	scheduleThread(
	    createIOThread(RtsFlags.GcFlags.initialStkSize, 
			   rts_apply((StgClosure *)handler,
				     rts_mkInt(stg_pending_buf[stg_pending_events]))));
    }
    unblockUserSignals();
}


/*
 * Function: markSignalHandlers()
 *
 * Evacuate the handler stack. _Assumes_ that console event delivery
 * has already been blocked.
 */
void markSignalHandlers (evac_fn evac)
{
    if (console_handler >= 0) {
	StgPtr p = deRefStablePtr((StgStablePtr)console_handler);
	evac((StgClosure**)&p);
    }
}


/*
 * Function: handleSignalsInThisThread()
 * 
 * Have current (OS) thread assume responsibility of handling console events/signals.
 * Currently not used (by the console event handling code.)
 */
void handleSignalsInThisThread(void)
{
    return;
}

/* 
 * Function: generic_handler()
 *
 * Local function which handles incoming console event (done in a sep OS thread),
 * recording the event in stg_pending_events. 
 */
static BOOL WINAPI generic_handler(DWORD dwCtrlType)
{
    /* Ultra-simple -- up the counter + signal a switch. */
sof's avatar
sof committed
203
204
205
206
207
208
209
210
211
212
    switch(dwCtrlType) {
    case CTRL_CLOSE_EVENT:
	/* Don't support the delivery of this event; if we
	 * indicate that we've handled it here and the Haskell handler
	 * doesn't take proper action (e.g., terminate the OS process),
	 * the user of the app will be unable to kill/close it. Not
	 * good, so disable the delivery for now.
	 */
	return FALSE;
    default:
sof's avatar
sof committed
213
214
	if (!deliver_event) return TRUE;

sof's avatar
sof committed
215
216
217
218
	if ( stg_pending_events < N_PENDING_EVENTS ) {
	    stg_pending_buf[stg_pending_events] = dwCtrlType;
	    stg_pending_events++;
	}
sof's avatar
sof committed
219
220
221
	/* Cheesy pulsing of an event to wake up a waiting RTS thread, if any */
	abandonRequestWait();
	resetAbandonRequestWait();
sof's avatar
sof committed
222
	return TRUE;
sof's avatar
sof committed
223
224
225
226
227
    }
}


/*
sof's avatar
sof committed
228
 * Function: rts_InstallConsoleEvent()
sof's avatar
sof committed
229
230
231
232
 *
 * Install/remove a console event handler.
 */
int
sof's avatar
sof committed
233
rts_InstallConsoleEvent(int action, StgStablePtr *handler)
sof's avatar
sof committed
234
235
236
237
238
239
240
{
    StgInt previous_hdlr = console_handler;

    switch (action) {
    case STG_SIG_IGN:
	console_handler = STG_SIG_IGN;
	if ( !SetConsoleCtrlHandler(NULL, TRUE) ) {
241
	    errorBelch("warning: unable to ignore console events");
sof's avatar
sof committed
242
243
244
245
246
	}
	break;
    case STG_SIG_DFL:
	console_handler = STG_SIG_IGN;
	if ( !SetConsoleCtrlHandler(NULL, FALSE) ) {
247
	    errorBelch("warning: unable to restore default console event handling");
sof's avatar
sof committed
248
249
250
251
	}
	break;
    case STG_SIG_HAN:
	console_handler = (StgInt)*handler;
sof's avatar
sof committed
252
253
254
	if ( previous_hdlr < 0 ) {
	  /* Only install generic_handler() once */
	  if ( !SetConsoleCtrlHandler(generic_handler, TRUE) ) {
255
	    errorBelch("warning: unable to install console event handler");
sof's avatar
sof committed
256
	  }
sof's avatar
sof committed
257
258
259
260
261
262
263
264
265
266
267
268
	}
	break;
    }
    
    if (previous_hdlr == STG_SIG_DFL || 
	previous_hdlr == STG_SIG_IGN) {
	return previous_hdlr;
    } else {
	*handler = (StgStablePtr)previous_hdlr;
	return STG_SIG_HAN;
    }
}
sof's avatar
sof committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293

/*
 * Function: rts_HandledConsoleEvent()
 *
 * Signal that a Haskell console event handler has completed its run.
 * The explicit notification that a Haskell handler has completed is 
 * required to better handle the delivery of Ctrl-C/Break events whilst
 * an async worker thread is handling a read request on stdin. The 
 * Win32 console implementation will abort such a read request when Ctrl-C
 * is delivered. That leaves the worker thread in a bind: should it 
 * abandon the request (the Haskell thread reading from stdin has been 
 * thrown an exception to signal the delivery of Ctrl-C & hence have 
 * aborted the I/O request) or simply ignore the aborted read and retry?
 * (the Haskell thread reading from stdin isn't concerned with the
 * delivery and handling of Ctrl-C.) With both scenarios being
 * possible, the worker thread needs to be told -- that is, did the
 * console event handler cause the IO request to be abandoned? 
 *
 */
void
rts_ConsoleHandlerDone(int ev)
{
    if ( (DWORD)ev == CTRL_BREAK_EVENT ||
	 (DWORD)ev == CTRL_C_EVENT ) {
	/* only these two cause stdin system calls to abort.. */
sof's avatar
sof committed
294
295
296
	SetEvent(hConsoleEvent); /* event is manual-reset */
	Sleep(0); /* yield */
	ResetEvent(hConsoleEvent); /* turn it back off again */
sof's avatar
sof committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    }
}

/*
 * Function: rts_waitConsoleHandlerCompletion()
 *
 * Esoteric entry point used by worker thread that got woken
 * up as part Ctrl-C delivery.
 */
int
rts_waitConsoleHandlerCompletion()
{
    /* As long as the worker doesn't need to do a multiple wait,
     * let's keep this HANDLE private to this 'module'.
     */
    return (WaitForSingleObject(hConsoleEvent, INFINITE) == WAIT_OBJECT_0);
}