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 typedef enum { HT_INPUT, HT_OUTPUT, HT_FOREIGN } HandleType;
70 /* ----------------------------------------------------------------------
75 * Data required by an input thread.
79 * Copy of the handle_generic structure.
81 HANDLE h; /* the handle itself */
82 HANDLE ev_to_main; /* event used to signal main thread */
83 HANDLE ev_from_main; /* event used to signal back to us */
84 int moribund; /* are we going to kill this soon? */
85 int done; /* request subthread to terminate */
86 int defunct; /* has the subthread already gone? */
87 int busy; /* operation currently in progress? */
88 void *privdata; /* for client to remember who they are */
91 * Data set at initialisation and then read-only.
96 * Data set by the input thread before signalling ev_to_main,
97 * and read by the main thread after receiving that signal.
99 char buffer[4096]; /* the data read from the handle */
100 DWORD len; /* how much data that was */
101 int readerr; /* lets us know about read errors */
104 * Callback function called by this module when data arrives on
107 handle_inputfn_t gotdata;
111 * The actual thread procedure for an input thread.
113 static DWORD WINAPI handle_input_threadfunc(void *param)
115 struct handle_input *ctx = (struct handle_input *) param;
116 OVERLAPPED ovl, *povl;
118 int readret, readlen;
120 if (ctx->flags & HANDLE_FLAG_OVERLAPPED) {
122 oev = CreateEvent(NULL, TRUE, FALSE, NULL);
127 if (ctx->flags & HANDLE_FLAG_UNITBUFFER)
130 readlen = sizeof(ctx->buffer);
134 memset(povl, 0, sizeof(OVERLAPPED));
137 readret = ReadFile(ctx->h, ctx->buffer,readlen, &ctx->len, povl);
139 ctx->readerr = GetLastError();
142 if (povl && !readret && ctx->readerr == ERROR_IO_PENDING) {
143 WaitForSingleObject(povl->hEvent, INFINITE);
144 readret = GetOverlappedResult(ctx->h, povl, &ctx->len, FALSE);
146 ctx->readerr = GetLastError();
153 * Windows apparently sends ERROR_BROKEN_PIPE when a
154 * pipe we're reading from is closed normally from the
155 * writing end. This is ludicrous; if that situation
156 * isn't a natural EOF, _nothing_ is. So if we get that
157 * particular error, we pretend it's EOF.
159 if (ctx->readerr == ERROR_BROKEN_PIPE)
164 if (readret && ctx->len == 0 &&
165 (ctx->flags & HANDLE_FLAG_IGNOREEOF))
168 SetEvent(ctx->ev_to_main);
173 WaitForSingleObject(ctx->ev_from_main, INFINITE);
175 SetEvent(ctx->ev_to_main);
176 break; /* main thread told us to shut down */
187 * This is called after a succcessful read, or from the
188 * `unthrottle' function. It decides whether or not to begin a new
191 static void handle_throttle(struct handle_input *ctx, int backlog)
197 * If there's a read operation already in progress, do nothing:
198 * when that completes, we'll come back here and be in a
199 * position to make a better decision.
205 * Otherwise, we must decide whether to start a new read based
206 * on the size of the backlog.
208 if (backlog < MAX_BACKLOG) {
209 SetEvent(ctx->ev_from_main);
214 /* ----------------------------------------------------------------------
219 * Data required by an output thread.
221 struct handle_output {
223 * Copy of the handle_generic structure.
225 HANDLE h; /* the handle itself */
226 HANDLE ev_to_main; /* event used to signal main thread */
227 HANDLE ev_from_main; /* event used to signal back to us */
228 int moribund; /* are we going to kill this soon? */
229 int done; /* request subthread to terminate */
230 int defunct; /* has the subthread already gone? */
231 int busy; /* operation currently in progress? */
232 void *privdata; /* for client to remember who they are */
235 * Data set at initialisation and then read-only.
240 * Data set by the main thread before signalling ev_from_main,
241 * and read by the input thread after receiving that signal.
243 char *buffer; /* the data to write */
244 DWORD len; /* how much data there is */
247 * Data set by the input thread before signalling ev_to_main,
248 * and read by the main thread after receiving that signal.
250 DWORD lenwritten; /* how much data we actually wrote */
251 int writeerr; /* return value from WriteFile */
254 * Data only ever read or written by the main thread.
256 bufchain queued_data; /* data still waiting to be written */
257 enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
260 * Callback function called when the backlog in the bufchain
263 handle_outputfn_t sentdata;
266 static DWORD WINAPI handle_output_threadfunc(void *param)
268 struct handle_output *ctx = (struct handle_output *) param;
269 OVERLAPPED ovl, *povl;
273 if (ctx->flags & HANDLE_FLAG_OVERLAPPED) {
275 oev = CreateEvent(NULL, TRUE, FALSE, NULL);
281 WaitForSingleObject(ctx->ev_from_main, INFINITE);
283 SetEvent(ctx->ev_to_main);
287 memset(povl, 0, sizeof(OVERLAPPED));
291 writeret = WriteFile(ctx->h, ctx->buffer, ctx->len,
292 &ctx->lenwritten, povl);
294 ctx->writeerr = GetLastError();
297 if (povl && !writeret && GetLastError() == ERROR_IO_PENDING) {
298 writeret = GetOverlappedResult(ctx->h, povl,
299 &ctx->lenwritten, TRUE);
301 ctx->writeerr = GetLastError();
306 SetEvent(ctx->ev_to_main);
317 static void handle_try_output(struct handle_output *ctx)
322 if (!ctx->busy && bufchain_size(&ctx->queued_data)) {
323 bufchain_prefix(&ctx->queued_data, &senddata, &sendlen);
324 ctx->buffer = senddata;
326 SetEvent(ctx->ev_from_main);
328 } else if (!ctx->busy && bufchain_size(&ctx->queued_data) == 0 &&
329 ctx->outgoingeof == EOF_PENDING) {
331 ctx->h = INVALID_HANDLE_VALUE;
332 ctx->outgoingeof = EOF_SENT;
336 /* ----------------------------------------------------------------------
337 * 'Foreign events'. These are handle structures which just contain a
338 * single event object passed to us by another module such as
339 * winnps.c, so that they can make use of our handle_get_events /
340 * handle_got_event mechanism for communicating with application main
343 struct handle_foreign {
345 * Copy of the handle_generic structure.
347 HANDLE h; /* the handle itself */
348 HANDLE ev_to_main; /* event used to signal main thread */
349 HANDLE ev_from_main; /* event used to signal back to us */
350 int moribund; /* are we going to kill this soon? */
351 int done; /* request subthread to terminate */
352 int defunct; /* has the subthread already gone? */
353 int busy; /* operation currently in progress? */
354 void *privdata; /* for client to remember who they are */
357 * Our own data, just consisting of knowledge of who to call back.
359 void (*callback)(void *);
363 /* ----------------------------------------------------------------------
364 * Unified code handling both input and output threads.
370 struct handle_generic g;
371 struct handle_input i;
372 struct handle_output o;
373 struct handle_foreign f;
377 static tree234 *handles_by_evtomain;
379 static int handle_cmp_evtomain(void *av, void *bv)
381 struct handle *a = (struct handle *)av;
382 struct handle *b = (struct handle *)bv;
384 if ((unsigned)a->u.g.ev_to_main < (unsigned)b->u.g.ev_to_main)
386 else if ((unsigned)a->u.g.ev_to_main > (unsigned)b->u.g.ev_to_main)
392 static int handle_find_evtomain(void *av, void *bv)
394 HANDLE *a = (HANDLE *)av;
395 struct handle *b = (struct handle *)bv;
397 if ((unsigned)*a < (unsigned)b->u.g.ev_to_main)
399 else if ((unsigned)*a > (unsigned)b->u.g.ev_to_main)
405 struct handle *handle_input_new(HANDLE handle, handle_inputfn_t gotdata,
406 void *privdata, int flags)
408 struct handle *h = snew(struct handle);
409 DWORD in_threadid; /* required for Win9x */
413 h->u.i.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);
414 h->u.i.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);
415 h->u.i.gotdata = gotdata;
416 h->u.i.defunct = FALSE;
417 h->u.i.moribund = FALSE;
419 h->u.i.privdata = privdata;
420 h->u.i.flags = flags;
422 if (!handles_by_evtomain)
423 handles_by_evtomain = newtree234(handle_cmp_evtomain);
424 add234(handles_by_evtomain, h);
426 CreateThread(NULL, 0, handle_input_threadfunc,
427 &h->u.i, 0, &in_threadid);
433 struct handle *handle_output_new(HANDLE handle, handle_outputfn_t sentdata,
434 void *privdata, int flags)
436 struct handle *h = snew(struct handle);
437 DWORD out_threadid; /* required for Win9x */
441 h->u.o.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);
442 h->u.o.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);
444 h->u.o.defunct = FALSE;
445 h->u.o.moribund = FALSE;
447 h->u.o.privdata = privdata;
448 bufchain_init(&h->u.o.queued_data);
449 h->u.o.outgoingeof = EOF_NO;
450 h->u.o.sentdata = sentdata;
451 h->u.o.flags = flags;
453 if (!handles_by_evtomain)
454 handles_by_evtomain = newtree234(handle_cmp_evtomain);
455 add234(handles_by_evtomain, h);
457 CreateThread(NULL, 0, handle_output_threadfunc,
458 &h->u.o, 0, &out_threadid);
463 struct handle *handle_add_foreign_event(HANDLE event,
464 void (*callback)(void *), void *ctx)
466 struct handle *h = snew(struct handle);
468 h->type = HT_FOREIGN;
469 h->u.f.h = INVALID_HANDLE_VALUE;
470 h->u.f.ev_to_main = event;
471 h->u.f.ev_from_main = INVALID_HANDLE_VALUE;
472 h->u.f.defunct = TRUE; /* we have no thread in the first place */
473 h->u.f.moribund = FALSE;
475 h->u.f.privdata = NULL;
476 h->u.f.callback = callback;
480 if (!handles_by_evtomain)
481 handles_by_evtomain = newtree234(handle_cmp_evtomain);
482 add234(handles_by_evtomain, h);
487 int handle_write(struct handle *h, const void *data, int len)
489 assert(h->type == HT_OUTPUT);
490 assert(h->u.o.outgoingeof == EOF_NO);
491 bufchain_add(&h->u.o.queued_data, data, len);
492 handle_try_output(&h->u.o);
493 return bufchain_size(&h->u.o.queued_data);
496 void handle_write_eof(struct handle *h)
499 * This function is called when we want to proactively send an
500 * end-of-file notification on the handle. We can only do this by
501 * actually closing the handle - so never call this on a
502 * bidirectional handle if we're still interested in its incoming
505 assert(h->type == HT_OUTPUT);
506 if (!h->u.o.outgoingeof == EOF_NO) {
507 h->u.o.outgoingeof = EOF_PENDING;
508 handle_try_output(&h->u.o);
512 HANDLE *handle_get_events(int *nevents)
519 * Go through our tree counting the handle objects currently
520 * engaged in useful activity.
524 if (handles_by_evtomain) {
525 for (i = 0; (h = index234(handles_by_evtomain, i)) != NULL; i++) {
529 ret = sresize(ret, size, HANDLE);
531 ret[n++] = h->u.g.ev_to_main;
540 static void handle_destroy(struct handle *h)
542 if (h->type == HT_OUTPUT)
543 bufchain_clear(&h->u.o.queued_data);
544 CloseHandle(h->u.g.ev_from_main);
545 CloseHandle(h->u.g.ev_to_main);
546 del234(handles_by_evtomain, h);
550 void handle_free(struct handle *h)
553 * If the handle is currently busy, we cannot immediately free
554 * it. Instead we must wait until it's finished its current
555 * operation, because otherwise the subthread will write to
556 * invalid memory after we free its context from under it.
558 assert(h && !h->u.g.moribund);
561 * Just set the moribund flag, which will be noticed next
562 * time an operation completes.
564 h->u.g.moribund = TRUE;
565 } else if (h->u.g.defunct) {
567 * There isn't even a subthread; we can go straight to
573 * The subthread is alive but not busy, so we now signal it
574 * to die. Set the moribund flag to indicate that it will
575 * want destroying after that.
577 h->u.g.moribund = TRUE;
580 SetEvent(h->u.g.ev_from_main);
584 void handle_got_event(HANDLE event)
588 assert(handles_by_evtomain);
589 h = find234(handles_by_evtomain, &event, handle_find_evtomain);
592 * This isn't an error condition. If two or more event
593 * objects were signalled during the same select operation,
594 * and processing of the first caused the second handle to
595 * be closed, then it will sometimes happen that we receive
596 * an event notification here for a handle which is already
597 * deceased. In that situation we simply do nothing.
602 if (h->u.g.moribund) {
604 * A moribund handle is already treated as dead from the
605 * external user's point of view, so do nothing with the
606 * actual event. Just signal the thread to die if
607 * necessary, or destroy the handle if not.
614 SetEvent(h->u.g.ev_from_main);
626 * A signal on an input handle means data has arrived.
628 if (h->u.i.len == 0) {
630 * EOF, or (nearly equivalently) read error.
632 h->u.i.defunct = TRUE;
633 h->u.i.gotdata(h, NULL, -h->u.i.readerr);
635 backlog = h->u.i.gotdata(h, h->u.i.buffer, h->u.i.len);
636 handle_throttle(&h->u.i, backlog);
644 * A signal on an output handle means we have completed a
645 * write. Call the callback to indicate that the output
646 * buffer size has decreased, or to indicate an error.
648 if (h->u.o.writeerr) {
650 * Write error. Send a negative value to the callback,
651 * and mark the thread as defunct (because the output
652 * thread is terminating by now).
654 h->u.o.defunct = TRUE;
655 h->u.o.sentdata(h, -h->u.o.writeerr);
657 bufchain_consume(&h->u.o.queued_data, h->u.o.lenwritten);
658 h->u.o.sentdata(h, bufchain_size(&h->u.o.queued_data));
659 handle_try_output(&h->u.o);
664 /* Just call the callback. */
665 h->u.f.callback(h->u.f.ctx);
670 void handle_unthrottle(struct handle *h, int backlog)
672 assert(h->type == HT_INPUT);
673 handle_throttle(&h->u.i, backlog);
676 int handle_backlog(struct handle *h)
678 assert(h->type == HT_OUTPUT);
679 return bufchain_size(&h->u.o.queued_data);
682 void *handle_get_privdata(struct handle *h)
684 return h->u.g.privdata;