2 * winhandl.c: Module to give Windows front ends the general
3 * ability to deal with consoles, pipes, serial ports, or any other
4 * type of data stream accessed through a Windows API HANDLE rather
5 * than a WinSock SOCKET.
7 * We do this by spawning a subthread to continuously try to read
8 * from the handle. Every time a read successfully returns some
9 * data, the subthread sets an event object which is picked up by
10 * the main thread, and the main thread then sets an event in
11 * return to instruct the subthread to resume reading.
13 * Output works precisely the other way round, in a second
14 * subthread. The output subthread should not be attempting to
15 * write all the time, because it hasn't always got data _to_
16 * write; so the output thread waits for an event object notifying
17 * it to _attempt_ a write, and then it sets an event in return
20 * (It's terribly annoying having to spawn a subthread for each
21 * direction of each handle. Technically it isn't necessary for
22 * serial ports, since we could use overlapped I/O within the main
23 * thread and wait directly on the event objects in the OVERLAPPED
24 * structures. However, we can't use this trick for some types of
25 * file handle at all - for some reason Windows restricts use of
26 * OVERLAPPED to files which were opened with the overlapped flag -
27 * and so we must use threads for those. This being the case, it's
28 * simplest just to use threads for everything rather than trying
29 * to keep track of multiple completely separate mechanisms.)
36 /* ----------------------------------------------------------------------
37 * Generic definitions.
41 * Maximum amount of backlog we will allow to build up on an input
42 * handle before we stop reading from it.
44 #define MAX_BACKLOG 32768
46 struct handle_generic
{
48 * Initial fields common to both handle_input and handle_output
51 * The three HANDLEs are set up at initialisation time and are
52 * thereafter read-only to both main thread and subthread.
53 * `moribund' is only used by the main thread; `done' is
54 * written by the main thread before signalling to the
55 * subthread. `defunct' and `busy' are used only by the main
58 HANDLE h
; /* the handle itself */
59 HANDLE ev_to_main
; /* event used to signal main thread */
60 HANDLE ev_from_main
; /* event used to signal back to us */
61 int moribund
; /* are we going to kill this soon? */
62 int done
; /* request subthread to terminate */
63 int defunct
; /* has the subthread already gone? */
64 int busy
; /* operation currently in progress? */
65 void *privdata
; /* for client to remember who they are */
68 /* ----------------------------------------------------------------------
73 * Data required by an input thread.
77 * Copy of the handle_generic structure.
79 HANDLE h
; /* the handle itself */
80 HANDLE ev_to_main
; /* event used to signal main thread */
81 HANDLE ev_from_main
; /* event used to signal back to us */
82 int moribund
; /* are we going to kill this soon? */
83 int done
; /* request subthread to terminate */
84 int defunct
; /* has the subthread already gone? */
85 int busy
; /* operation currently in progress? */
86 void *privdata
; /* for client to remember who they are */
89 * Data set at initialisation and then read-only.
94 * Data set by the input thread before signalling ev_to_main,
95 * and read by the main thread after receiving that signal.
97 char buffer
[4096]; /* the data read from the handle */
98 DWORD len
; /* how much data that was */
99 int readret
; /* lets us know about read errors */
102 * Callback function called by this module when data arrives on
105 handle_inputfn_t gotdata
;
109 * The actual thread procedure for an input thread.
111 static DWORD WINAPI
handle_input_threadfunc(void *param
)
113 struct handle_input
*ctx
= (struct handle_input
*) param
;
114 OVERLAPPED ovl
, *povl
;
118 if (ctx
->flags
& HANDLE_FLAG_OVERLAPPED
) {
120 oev
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
125 if (ctx
->flags
& HANDLE_FLAG_UNITBUFFER
)
128 readlen
= sizeof(ctx
->buffer
);
132 memset(povl
, 0, sizeof(OVERLAPPED
));
135 ctx
->readret
= ReadFile(ctx
->h
, ctx
->buffer
, readlen
,
138 error
= GetLastError();
139 if (povl
&& !ctx
->readret
&& error
== ERROR_IO_PENDING
) {
140 WaitForSingleObject(povl
->hEvent
, INFINITE
);
141 ctx
->readret
= GetOverlappedResult(ctx
->h
, povl
, &ctx
->len
, FALSE
);
146 * Windows apparently sends ERROR_BROKEN_PIPE when a
147 * pipe we're reading from is closed normally from the
148 * writing end. This is ludicrous; if that situation
149 * isn't a natural EOF, _nothing_ is. So if we get that
150 * particular error, we pretend it's EOF.
152 if (error
== ERROR_BROKEN_PIPE
)
157 if (ctx
->readret
&& ctx
->len
== 0 &&
158 (ctx
->flags
& HANDLE_FLAG_IGNOREEOF
))
161 SetEvent(ctx
->ev_to_main
);
166 WaitForSingleObject(ctx
->ev_from_main
, INFINITE
);
168 break; /* main thread told us to shut down */
178 * This is called after a succcessful read, or from the
179 * `unthrottle' function. It decides whether or not to begin a new
182 static void handle_throttle(struct handle_input
*ctx
, int backlog
)
188 * If there's a read operation already in progress, do nothing:
189 * when that completes, we'll come back here and be in a
190 * position to make a better decision.
196 * Otherwise, we must decide whether to start a new read based
197 * on the size of the backlog.
199 if (backlog
< MAX_BACKLOG
) {
200 SetEvent(ctx
->ev_from_main
);
205 /* ----------------------------------------------------------------------
210 * Data required by an output thread.
212 struct handle_output
{
214 * Copy of the handle_generic structure.
216 HANDLE h
; /* the handle itself */
217 HANDLE ev_to_main
; /* event used to signal main thread */
218 HANDLE ev_from_main
; /* event used to signal back to us */
219 int moribund
; /* are we going to kill this soon? */
220 int done
; /* request subthread to terminate */
221 int defunct
; /* has the subthread already gone? */
222 int busy
; /* operation currently in progress? */
223 void *privdata
; /* for client to remember who they are */
226 * Data set at initialisation and then read-only.
231 * Data set by the main thread before signalling ev_from_main,
232 * and read by the input thread after receiving that signal.
234 char *buffer
; /* the data to write */
235 DWORD len
; /* how much data there is */
238 * Data set by the input thread before signalling ev_to_main,
239 * and read by the main thread after receiving that signal.
241 DWORD lenwritten
; /* how much data we actually wrote */
242 int writeret
; /* return value from WriteFile */
245 * Data only ever read or written by the main thread.
247 bufchain queued_data
; /* data still waiting to be written */
250 * Callback function called when the backlog in the bufchain
253 handle_outputfn_t sentdata
;
256 static DWORD WINAPI
handle_output_threadfunc(void *param
)
258 struct handle_output
*ctx
= (struct handle_output
*) param
;
259 OVERLAPPED ovl
, *povl
;
261 if (ctx
->flags
& HANDLE_FLAG_OVERLAPPED
)
267 WaitForSingleObject(ctx
->ev_from_main
, INFINITE
);
269 SetEvent(ctx
->ev_to_main
);
273 memset(povl
, 0, sizeof(OVERLAPPED
));
274 ctx
->writeret
= WriteFile(ctx
->h
, ctx
->buffer
, ctx
->len
,
275 &ctx
->lenwritten
, povl
);
276 if (povl
&& !ctx
->writeret
&& GetLastError() == ERROR_IO_PENDING
)
277 ctx
->writeret
= GetOverlappedResult(ctx
->h
, povl
,
278 &ctx
->lenwritten
, TRUE
);
280 SetEvent(ctx
->ev_to_main
);
288 static void handle_try_output(struct handle_output
*ctx
)
293 if (!ctx
->busy
&& bufchain_size(&ctx
->queued_data
)) {
294 bufchain_prefix(&ctx
->queued_data
, &senddata
, &sendlen
);
295 ctx
->buffer
= senddata
;
297 SetEvent(ctx
->ev_from_main
);
302 /* ----------------------------------------------------------------------
303 * Unified code handling both input and output threads.
309 struct handle_generic g
;
310 struct handle_input i
;
311 struct handle_output o
;
315 static tree234
*handles_by_evtomain
;
317 static int handle_cmp_evtomain(void *av
, void *bv
)
319 struct handle
*a
= (struct handle
*)av
;
320 struct handle
*b
= (struct handle
*)bv
;
322 if ((unsigned)a
->u
.g
.ev_to_main
< (unsigned)b
->u
.g
.ev_to_main
)
324 else if ((unsigned)a
->u
.g
.ev_to_main
> (unsigned)b
->u
.g
.ev_to_main
)
330 static int handle_find_evtomain(void *av
, void *bv
)
332 HANDLE
*a
= (HANDLE
*)av
;
333 struct handle
*b
= (struct handle
*)bv
;
335 if ((unsigned)*a
< (unsigned)b
->u
.g
.ev_to_main
)
337 else if ((unsigned)*a
> (unsigned)b
->u
.g
.ev_to_main
)
343 struct handle
*handle_input_new(HANDLE handle
, handle_inputfn_t gotdata
,
344 void *privdata
, int flags
)
346 struct handle
*h
= snew(struct handle
);
347 DWORD in_threadid
; /* required for Win9x */
351 h
->u
.i
.ev_to_main
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
352 h
->u
.i
.ev_from_main
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
353 h
->u
.i
.gotdata
= gotdata
;
354 h
->u
.i
.defunct
= FALSE
;
355 h
->u
.i
.moribund
= FALSE
;
357 h
->u
.i
.privdata
= privdata
;
358 h
->u
.i
.flags
= flags
;
360 if (!handles_by_evtomain
)
361 handles_by_evtomain
= newtree234(handle_cmp_evtomain
);
362 add234(handles_by_evtomain
, h
);
364 CreateThread(NULL
, 0, handle_input_threadfunc
,
365 &h
->u
.i
, 0, &in_threadid
);
371 struct handle
*handle_output_new(HANDLE handle
, handle_outputfn_t sentdata
,
372 void *privdata
, int flags
)
374 struct handle
*h
= snew(struct handle
);
375 DWORD out_threadid
; /* required for Win9x */
379 h
->u
.o
.ev_to_main
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
380 h
->u
.o
.ev_from_main
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
382 h
->u
.o
.defunct
= FALSE
;
383 h
->u
.o
.moribund
= FALSE
;
385 h
->u
.o
.privdata
= privdata
;
386 bufchain_init(&h
->u
.o
.queued_data
);
387 h
->u
.o
.sentdata
= sentdata
;
388 h
->u
.o
.flags
= flags
;
390 if (!handles_by_evtomain
)
391 handles_by_evtomain
= newtree234(handle_cmp_evtomain
);
392 add234(handles_by_evtomain
, h
);
394 CreateThread(NULL
, 0, handle_output_threadfunc
,
395 &h
->u
.i
, 0, &out_threadid
);
400 int handle_write(struct handle
*h
, const void *data
, int len
)
403 bufchain_add(&h
->u
.o
.queued_data
, data
, len
);
404 handle_try_output(&h
->u
.o
);
405 return bufchain_size(&h
->u
.o
.queued_data
);
408 HANDLE
*handle_get_events(int *nevents
)
415 * Go through our tree counting the handle objects currently
416 * engaged in useful activity.
420 if (handles_by_evtomain
) {
421 for (i
= 0; (h
= index234(handles_by_evtomain
, i
)) != NULL
; i
++) {
425 ret
= sresize(ret
, size
, HANDLE
);
427 ret
[n
++] = h
->u
.g
.ev_to_main
;
436 static void handle_destroy(struct handle
*h
)
439 bufchain_clear(&h
->u
.o
.queued_data
);
440 CloseHandle(h
->u
.g
.ev_from_main
);
441 CloseHandle(h
->u
.g
.ev_to_main
);
442 del234(handles_by_evtomain
, h
);
446 void handle_free(struct handle
*h
)
449 * If the handle is currently busy, we cannot immediately free
450 * it. Instead we must wait until it's finished its current
451 * operation, because otherwise the subthread will write to
452 * invalid memory after we free its context from under it.
454 assert(h
&& !h
->u
.g
.moribund
);
457 * Just set the moribund flag, which will be noticed next
458 * time an operation completes.
460 h
->u
.g
.moribund
= TRUE
;
461 } else if (h
->u
.g
.defunct
) {
463 * There isn't even a subthread; we can go straight to
469 * The subthread is alive but not busy, so we now signal it
470 * to die. Set the moribund flag to indicate that it will
471 * want destroying after that.
473 h
->u
.g
.moribund
= TRUE
;
476 SetEvent(h
->u
.g
.ev_from_main
);
480 void handle_got_event(HANDLE event
)
484 assert(handles_by_evtomain
);
485 h
= find234(handles_by_evtomain
, &event
, handle_find_evtomain
);
488 * This isn't an error condition. If two or more event
489 * objects were signalled during the same select operation,
490 * and processing of the first caused the second handle to
491 * be closed, then it will sometimes happen that we receive
492 * an event notification here for a handle which is already
493 * deceased. In that situation we simply do nothing.
498 if (h
->u
.g
.moribund
) {
500 * A moribund handle is already treated as dead from the
501 * external user's point of view, so do nothing with the
502 * actual event. Just signal the thread to die if
503 * necessary, or destroy the handle if not.
510 SetEvent(h
->u
.g
.ev_from_main
);
521 * A signal on an input handle means data has arrived.
523 if (h
->u
.i
.len
== 0) {
525 * EOF, or (nearly equivalently) read error.
527 h
->u
.i
.gotdata(h
, NULL
, (h
->u
.i
.readret ?
0 : -1));
528 h
->u
.i
.defunct
= TRUE
;
530 backlog
= h
->u
.i
.gotdata(h
, h
->u
.i
.buffer
, h
->u
.i
.len
);
531 handle_throttle(&h
->u
.i
, backlog
);
537 * A signal on an output handle means we have completed a
538 * write. Call the callback to indicate that the output
539 * buffer size has decreased, or to indicate an error.
541 if (!h
->u
.o
.writeret
) {
543 * Write error. Send a negative value to the callback,
544 * and mark the thread as defunct (because the output
545 * thread is terminating by now).
547 h
->u
.o
.sentdata(h
, -1);
548 h
->u
.o
.defunct
= TRUE
;
550 bufchain_consume(&h
->u
.o
.queued_data
, h
->u
.o
.lenwritten
);
551 h
->u
.o
.sentdata(h
, bufchain_size(&h
->u
.o
.queued_data
));
552 handle_try_output(&h
->u
.o
);
557 void handle_unthrottle(struct handle
*h
, int backlog
)
560 handle_throttle(&h
->u
.i
, backlog
);
563 int handle_backlog(struct handle
*h
)
566 return bufchain_size(&h
->u
.o
.queued_data
);
569 void *handle_get_privdata(struct handle
*h
)
571 return h
->u
.g
.privdata
;