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 break; /* main thread told us to shut down */
185 * This is called after a succcessful read, or from the
186 * `unthrottle' function. It decides whether or not to begin a new
189 static void handle_throttle(struct handle_input *ctx, int backlog)
195 * If there's a read operation already in progress, do nothing:
196 * when that completes, we'll come back here and be in a
197 * position to make a better decision.
203 * Otherwise, we must decide whether to start a new read based
204 * on the size of the backlog.
206 if (backlog < MAX_BACKLOG) {
207 SetEvent(ctx->ev_from_main);
212 /* ----------------------------------------------------------------------
217 * Data required by an output thread.
219 struct handle_output {
221 * Copy of the handle_generic structure.
223 HANDLE h; /* the handle itself */
224 HANDLE ev_to_main; /* event used to signal main thread */
225 HANDLE ev_from_main; /* event used to signal back to us */
226 int moribund; /* are we going to kill this soon? */
227 int done; /* request subthread to terminate */
228 int defunct; /* has the subthread already gone? */
229 int busy; /* operation currently in progress? */
230 void *privdata; /* for client to remember who they are */
233 * Data set at initialisation and then read-only.
238 * Data set by the main thread before signalling ev_from_main,
239 * and read by the input thread after receiving that signal.
241 char *buffer; /* the data to write */
242 DWORD len; /* how much data there is */
245 * Data set by the input thread before signalling ev_to_main,
246 * and read by the main thread after receiving that signal.
248 DWORD lenwritten; /* how much data we actually wrote */
249 int writeerr; /* return value from WriteFile */
252 * Data only ever read or written by the main thread.
254 bufchain queued_data; /* data still waiting to be written */
255 enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
258 * Callback function called when the backlog in the bufchain
261 handle_outputfn_t sentdata;
264 static DWORD WINAPI handle_output_threadfunc(void *param)
266 struct handle_output *ctx = (struct handle_output *) param;
267 OVERLAPPED ovl, *povl;
271 if (ctx->flags & HANDLE_FLAG_OVERLAPPED) {
273 oev = CreateEvent(NULL, TRUE, FALSE, NULL);
279 WaitForSingleObject(ctx->ev_from_main, INFINITE);
281 SetEvent(ctx->ev_to_main);
285 memset(povl, 0, sizeof(OVERLAPPED));
289 writeret = WriteFile(ctx->h, ctx->buffer, ctx->len,
290 &ctx->lenwritten, povl);
292 ctx->writeerr = GetLastError();
295 if (povl && !writeret && GetLastError() == ERROR_IO_PENDING) {
296 writeret = GetOverlappedResult(ctx->h, povl,
297 &ctx->lenwritten, TRUE);
299 ctx->writeerr = GetLastError();
304 SetEvent(ctx->ev_to_main);
315 static void handle_try_output(struct handle_output *ctx)
320 if (!ctx->busy && bufchain_size(&ctx->queued_data)) {
321 bufchain_prefix(&ctx->queued_data, &senddata, &sendlen);
322 ctx->buffer = senddata;
324 SetEvent(ctx->ev_from_main);
326 } else if (!ctx->busy && bufchain_size(&ctx->queued_data) == 0 &&
327 ctx->outgoingeof == EOF_PENDING) {
329 ctx->h = INVALID_HANDLE_VALUE;
330 ctx->outgoingeof = EOF_SENT;
334 /* ----------------------------------------------------------------------
335 * 'Foreign events'. These are handle structures which just contain a
336 * single event object passed to us by another module such as
337 * winnps.c, so that they can make use of our handle_get_events /
338 * handle_got_event mechanism for communicating with application main
341 struct handle_foreign {
343 * Copy of the handle_generic structure.
345 HANDLE h; /* the handle itself */
346 HANDLE ev_to_main; /* event used to signal main thread */
347 HANDLE ev_from_main; /* event used to signal back to us */
348 int moribund; /* are we going to kill this soon? */
349 int done; /* request subthread to terminate */
350 int defunct; /* has the subthread already gone? */
351 int busy; /* operation currently in progress? */
352 void *privdata; /* for client to remember who they are */
355 * Our own data, just consisting of knowledge of who to call back.
357 void (*callback)(void *);
361 /* ----------------------------------------------------------------------
362 * Unified code handling both input and output threads.
368 struct handle_generic g;
369 struct handle_input i;
370 struct handle_output o;
371 struct handle_foreign f;
375 static tree234 *handles_by_evtomain;
377 static int handle_cmp_evtomain(void *av, void *bv)
379 struct handle *a = (struct handle *)av;
380 struct handle *b = (struct handle *)bv;
382 if ((unsigned)a->u.g.ev_to_main < (unsigned)b->u.g.ev_to_main)
384 else if ((unsigned)a->u.g.ev_to_main > (unsigned)b->u.g.ev_to_main)
390 static int handle_find_evtomain(void *av, void *bv)
392 HANDLE *a = (HANDLE *)av;
393 struct handle *b = (struct handle *)bv;
395 if ((unsigned)*a < (unsigned)b->u.g.ev_to_main)
397 else if ((unsigned)*a > (unsigned)b->u.g.ev_to_main)
403 struct handle *handle_input_new(HANDLE handle, handle_inputfn_t gotdata,
404 void *privdata, int flags)
406 struct handle *h = snew(struct handle);
407 DWORD in_threadid; /* required for Win9x */
411 h->u.i.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);
412 h->u.i.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);
413 h->u.i.gotdata = gotdata;
414 h->u.i.defunct = FALSE;
415 h->u.i.moribund = FALSE;
417 h->u.i.privdata = privdata;
418 h->u.i.flags = flags;
420 if (!handles_by_evtomain)
421 handles_by_evtomain = newtree234(handle_cmp_evtomain);
422 add234(handles_by_evtomain, h);
424 CreateThread(NULL, 0, handle_input_threadfunc,
425 &h->u.i, 0, &in_threadid);
431 struct handle *handle_output_new(HANDLE handle, handle_outputfn_t sentdata,
432 void *privdata, int flags)
434 struct handle *h = snew(struct handle);
435 DWORD out_threadid; /* required for Win9x */
439 h->u.o.ev_to_main = CreateEvent(NULL, FALSE, FALSE, NULL);
440 h->u.o.ev_from_main = CreateEvent(NULL, FALSE, FALSE, NULL);
442 h->u.o.defunct = FALSE;
443 h->u.o.moribund = FALSE;
445 h->u.o.privdata = privdata;
446 bufchain_init(&h->u.o.queued_data);
447 h->u.o.outgoingeof = EOF_NO;
448 h->u.o.sentdata = sentdata;
449 h->u.o.flags = flags;
451 if (!handles_by_evtomain)
452 handles_by_evtomain = newtree234(handle_cmp_evtomain);
453 add234(handles_by_evtomain, h);
455 CreateThread(NULL, 0, handle_output_threadfunc,
456 &h->u.o, 0, &out_threadid);
461 struct handle *handle_add_foreign_event(HANDLE event,
462 void (*callback)(void *), void *ctx)
464 struct handle *h = snew(struct handle);
466 h->type = HT_FOREIGN;
467 h->u.f.h = INVALID_HANDLE_VALUE;
468 h->u.f.ev_to_main = event;
469 h->u.f.ev_from_main = INVALID_HANDLE_VALUE;
470 h->u.f.defunct = TRUE; /* we have no thread in the first place */
471 h->u.f.moribund = FALSE;
473 h->u.f.privdata = NULL;
474 h->u.f.callback = callback;
478 if (!handles_by_evtomain)
479 handles_by_evtomain = newtree234(handle_cmp_evtomain);
480 add234(handles_by_evtomain, h);
485 int handle_write(struct handle *h, const void *data, int len)
487 assert(h->type == HT_OUTPUT);
488 assert(h->u.o.outgoingeof == EOF_NO);
489 bufchain_add(&h->u.o.queued_data, data, len);
490 handle_try_output(&h->u.o);
491 return bufchain_size(&h->u.o.queued_data);
494 void handle_write_eof(struct handle *h)
497 * This function is called when we want to proactively send an
498 * end-of-file notification on the handle. We can only do this by
499 * actually closing the handle - so never call this on a
500 * bidirectional handle if we're still interested in its incoming
503 assert(h->type == HT_OUTPUT);
504 if (!h->u.o.outgoingeof == EOF_NO) {
505 h->u.o.outgoingeof = EOF_PENDING;
506 handle_try_output(&h->u.o);
510 HANDLE *handle_get_events(int *nevents)
517 * Go through our tree counting the handle objects currently
518 * engaged in useful activity.
522 if (handles_by_evtomain) {
523 for (i = 0; (h = index234(handles_by_evtomain, i)) != NULL; i++) {
527 ret = sresize(ret, size, HANDLE);
529 ret[n++] = h->u.g.ev_to_main;
538 static void handle_destroy(struct handle *h)
540 if (h->type == HT_OUTPUT)
541 bufchain_clear(&h->u.o.queued_data);
542 CloseHandle(h->u.g.ev_from_main);
543 CloseHandle(h->u.g.ev_to_main);
544 del234(handles_by_evtomain, h);
548 void handle_free(struct handle *h)
551 * If the handle is currently busy, we cannot immediately free
552 * it. Instead we must wait until it's finished its current
553 * operation, because otherwise the subthread will write to
554 * invalid memory after we free its context from under it.
556 assert(h && !h->u.g.moribund);
559 * Just set the moribund flag, which will be noticed next
560 * time an operation completes.
562 h->u.g.moribund = TRUE;
563 } else if (h->u.g.defunct) {
565 * There isn't even a subthread; we can go straight to
571 * The subthread is alive but not busy, so we now signal it
572 * to die. Set the moribund flag to indicate that it will
573 * want destroying after that.
575 h->u.g.moribund = TRUE;
578 SetEvent(h->u.g.ev_from_main);
582 void handle_got_event(HANDLE event)
586 assert(handles_by_evtomain);
587 h = find234(handles_by_evtomain, &event, handle_find_evtomain);
590 * This isn't an error condition. If two or more event
591 * objects were signalled during the same select operation,
592 * and processing of the first caused the second handle to
593 * be closed, then it will sometimes happen that we receive
594 * an event notification here for a handle which is already
595 * deceased. In that situation we simply do nothing.
600 if (h->u.g.moribund) {
602 * A moribund handle is already treated as dead from the
603 * external user's point of view, so do nothing with the
604 * actual event. Just signal the thread to die if
605 * necessary, or destroy the handle if not.
612 SetEvent(h->u.g.ev_from_main);
624 * A signal on an input handle means data has arrived.
626 if (h->u.i.len == 0) {
628 * EOF, or (nearly equivalently) read error.
630 h->u.i.gotdata(h, NULL, -h->u.i.readerr);
631 h->u.i.defunct = TRUE;
633 backlog = h->u.i.gotdata(h, h->u.i.buffer, h->u.i.len);
634 handle_throttle(&h->u.i, backlog);
642 * A signal on an output handle means we have completed a
643 * write. Call the callback to indicate that the output
644 * buffer size has decreased, or to indicate an error.
646 if (h->u.o.writeerr) {
648 * Write error. Send a negative value to the callback,
649 * and mark the thread as defunct (because the output
650 * thread is terminating by now).
652 h->u.o.sentdata(h, -h->u.o.writeerr);
653 h->u.o.defunct = TRUE;
655 bufchain_consume(&h->u.o.queued_data, h->u.o.lenwritten);
656 h->u.o.sentdata(h, bufchain_size(&h->u.o.queued_data));
657 handle_try_output(&h->u.o);
662 /* Just call the callback. */
663 h->u.f.callback(h->u.f.ctx);
668 void handle_unthrottle(struct handle *h, int backlog)
670 assert(h->type == HT_INPUT);
671 handle_throttle(&h->u.i, backlog);
674 int handle_backlog(struct handle *h)
676 assert(h->type == HT_OUTPUT);
677 return bufchain_size(&h->u.o.queued_data);
680 void *handle_get_privdata(struct handle *h)
682 return h->u.g.privdata;