OSDN Git Service

* select.cc (allocfd_set): Zero allocated fd_set.
[pf3gnuchains/pf3gnuchains4x.git] / winsup / cygwin / select.cc
1 /* select.cc
2
3    Copyright 1996, 1997, 1998, 1999, 2000 Red Hat, Inc.
4
5    Written by Christopher Faylor of Cygnus Solutions
6    cgf@cygnus.com
7
8 This file is part of Cygwin.
9
10 This software is a copyrighted work licensed under the terms of the
11 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
12 details. */
13
14 /*
15  * The following line means that the BSD socket
16  * definitions for fd_set, FD_ISSET etc. are used in this
17  * file.
18  */
19
20 #define  __INSIDE_CYGWIN_NET__
21 #define Win32_Winsock
22
23 #include "winsup.h"
24 #include <errno.h>
25 #include <sys/socket.h>
26 #include <stdlib.h>
27 #include <sys/time.h>
28
29 #include <wingdi.h>
30 #include <winuser.h>
31 #include <netdb.h>
32 #include <unistd.h>
33 #include <stdio.h>
34 #include <winsock.h>
35 #include "select.h"
36
37 /*
38  * All these defines below should be in sys/types.h
39  * but because of the includes above, they may not have
40  * been included. We create special UNIX_xxxx versions here.
41  */
42
43 #ifndef NBBY
44 #define NBBY 8    /* number of bits in a byte */
45 #endif /* NBBY */
46
47 /*
48  * Select uses bit masks of file descriptors in longs.
49  * These macros manipulate such bit fields (the filesystem macros use chars).
50  * FD_SETSIZE may be defined by the user, but the default here
51  * should be >= NOFILE (param.h).
52  */
53
54 typedef long fd_mask;
55 #define UNIX_NFDBITS (sizeof (fd_mask) * NBBY)       /* bits per mask */
56 #ifndef unix_howmany
57 #define unix_howmany(x,y) (((x)+((y)-1))/(y))
58 #endif
59
60 #define unix_fd_set fd_set
61
62 #define NULL_fd_set ((fd_set *)NULL)
63 #define sizeof_fd_set(n) \
64   ((unsigned) (NULL_fd_set->fds_bits + unix_howmany((n), UNIX_NFDBITS)))
65 #define UNIX_FD_SET(n, p) \
66   ((p)->fds_bits[(n)/UNIX_NFDBITS] |= (1L << ((n) % UNIX_NFDBITS)))
67 #define UNIX_FD_CLR(n, p) \
68   ((p)->fds_bits[(n)/UNIX_NFDBITS] &= ~(1L << ((n) % UNIX_NFDBITS)))
69 #define UNIX_FD_ISSET(n, p) \
70   ((p)->fds_bits[(n)/UNIX_NFDBITS] & (1L << ((n) % UNIX_NFDBITS)))
71 #define UNIX_FD_ZERO(p, n) \
72   bzero ((caddr_t)(p), sizeof_fd_set ((n)))
73
74 #define allocfd_set(n) ((fd_set *) memset (alloca (sizeof_fd_set (n)), 0, sizeof_fd_set (n)))
75 #define copyfd_set(to, from, n) memcpy (to, from, sizeof_fd_set (n));
76
77 /* Make a fhandler_foo::ready_for_ready method.
78    Assumption: The "ready_for_read" methods are called with one level of
79    signal blocking. */
80 #define MAKEready(what) \
81 int \
82 fhandler_##what::ready_for_read (int fd, DWORD howlong, int ignra) \
83 { \
84   select_record me (this); \
85   me.fd = fd; \
86   (void) select_read (&me); \
87   while (!peek_##what (&me, ignra) && howlong == INFINITE) \
88     if (fd >= 0 && dtable.not_open (fd)) \
89       break; \
90     else if (WaitForSingleObject (signal_arrived, 10) == WAIT_OBJECT_0) \
91       break; \
92   return me.read_ready; \
93 }
94
95 #define set_handle_or_return_if_not_open(h, s) \
96   h = (s)->fh->get_handle (); \
97   if (dtable.not_open ((s)->fd)) \
98     { \
99       (s)->saw_error = TRUE; \
100       set_errno (EBADF); \
101       return -1; \
102     } \
103
104 /* The main select code.
105  */
106 extern "C"
107 int
108 cygwin_select (int maxfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
109                struct timeval *to)
110 {
111   select_stuff sel;
112   fd_set *dummy_readfds = allocfd_set (maxfds);
113   fd_set *dummy_writefds = allocfd_set (maxfds);
114   fd_set *dummy_exceptfds = allocfd_set (maxfds);
115   sigframe thisframe (mainthread, 0);
116
117 #if 0
118   if (n > FD_SETSIZE)
119     {
120       set_errno (EINVAL);
121       return -1;
122     }
123 #endif
124
125   select_printf ("%d, %p, %p, %p, %p", maxfds, readfds, writefds, exceptfds, to);
126
127   if (!readfds)
128     readfds = dummy_readfds;
129   if (!writefds)
130     writefds = dummy_writefds;
131   if (!exceptfds)
132     exceptfds = dummy_exceptfds;
133
134   for (int i = 0; i < maxfds; i++)
135     if (!sel.test_and_set (i, readfds, writefds, exceptfds))
136       {
137         select_printf ("aborting due to test_and_set error");
138         return -1;      /* Invalid fd, maybe? */
139       }
140
141   /* Convert to milliseconds or INFINITE if to == NULL */
142   DWORD ms = to ? (to->tv_sec * 1000) + (to->tv_usec / 1000) : INFINITE;
143   if (ms == 0 && to->tv_usec)
144     ms = 1;                     /* At least 1 ms granularity */
145
146   if (to)
147     select_printf ("to->tv_sec %d, to->tv_usec %d, ms %d", to->tv_sec, to->tv_usec, ms);
148   else
149     select_printf ("to NULL, ms %x", ms);
150
151   select_printf ("sel.always_ready %d", sel.always_ready);
152
153   /* Degenerate case.  No fds to wait for.  Just wait. */
154   if (sel.start.next == NULL)
155     {
156       if (WaitForSingleObject (signal_arrived, ms) == WAIT_OBJECT_0)
157         {
158           select_printf ("signal received");
159           set_sig_errno (EINTR);
160           return -1;
161         }
162       return 0;
163     }
164
165   /* Allocate some fd_set structures using the number of fds as a guide. */
166   fd_set *r = allocfd_set (maxfds);
167   fd_set *w = allocfd_set (maxfds);
168   fd_set *e = allocfd_set (maxfds);
169
170   /* Don't bother waiting if one of the selected fds is "always ready". */
171   if ((!sel.always_ready || ms != 0) && sel.wait (r, w, e, ms))
172     return -1;  /* some kind of error */
173
174   copyfd_set (readfds, r, maxfds);
175   copyfd_set (writefds, w, maxfds);
176   copyfd_set (exceptfds, e, maxfds);
177   return sel.poll (readfds, writefds, exceptfds);
178 }
179
180 /* Cleanup */
181 select_stuff::~select_stuff ()
182 {
183   select_record *s = &start;
184
185   select_printf ("calling cleanup routines");
186   while ((s = s->next))
187     if (s->cleanup)
188       s->cleanup (s, this);
189
190   select_record *snext = start.next;
191
192   select_printf ("deleting select records");
193   while ((s = snext))
194     {
195       snext = s->next;
196       delete s;
197     }
198 }
199
200 /* Add a record to the select chain */
201 int
202 select_stuff::test_and_set (int i, fd_set *readfds, fd_set *writefds,
203                             fd_set *exceptfds)
204 {
205   select_record *s = NULL;
206   if (UNIX_FD_ISSET (i, readfds) && (s = dtable.select_read (i, s)) == NULL)
207     return 0; /* error */
208   if (UNIX_FD_ISSET (i, writefds) && (s = dtable.select_write (i, s)) == NULL)
209     return 0; /* error */
210   if (UNIX_FD_ISSET (i, exceptfds) && (s = dtable.select_except (i, s)) == NULL)
211     return 0; /* error */
212   if (s == NULL)
213     return 1; /* nothing to do */
214
215   if (s->read_ready || s->write_ready || s->except_ready)
216     always_ready = TRUE;
217
218   if (s->windows_handle || s->windows_handle || s->windows_handle)
219     windows_used = TRUE;
220
221   s->next = start.next;
222   start.next = s;
223   return 1;
224 }
225
226 /* Poll every fd in the select chain.  Set appropriate fd in mask. */
227 int
228 select_stuff::poll (fd_set *readfds, fd_set *writefds, fd_set *exceptfds)
229 {
230   int n = 0;
231   select_record *s = &start;
232   while ((s = s->next))
233     n += s->poll (s, readfds, writefds, exceptfds);
234   select_printf ("returning %d", n);
235   return n;
236 }
237
238 /* The heart of select.  Waits for an fd to do something interesting. */
239 int
240 select_stuff::wait (fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
241                     DWORD ms)
242 {
243   int wait_ret;
244   HANDLE w4[MAXIMUM_WAIT_OBJECTS];
245   select_record *s = &start;
246   int m = 0;
247
248   w4[m++] = signal_arrived;  /* Always wait for the arrival of a signal. */
249   /* Loop through the select chain, starting up anything appropriate and
250      counting the number of active fds. */
251   while ((s = s->next))
252     {
253       if (!s->startup (s, this))
254         {
255           __seterrno ();
256           return -1;
257         }
258       if (s->h == NULL)
259         continue;
260       for (int i = 1; i < m; i++)
261         if (w4[i] == s->h)
262           goto next_while;
263       w4[m++] = s->h;
264   next_while:
265       continue;
266     }
267
268   DWORD start_time = GetTickCount ();   /* Record the current time for later use. */
269
270   debug_printf ("m %d, ms %u", m, ms);
271   for (;;)
272     {
273       if (!windows_used)
274         wait_ret = WaitForMultipleObjects (m, w4, FALSE, ms);
275       else
276         wait_ret = MsgWaitForMultipleObjects (m, w4, FALSE, ms, QS_ALLINPUT);
277
278       switch (wait_ret)
279       {
280         case WAIT_OBJECT_0:
281           select_printf ("signal received");
282           set_sig_errno (EINTR);
283           return -1;
284         case WAIT_FAILED:
285           select_printf ("WaitForMultipleObjects failed");
286           __seterrno ();
287           return -1;
288         case WAIT_TIMEOUT:
289           select_printf ("timed out");
290           goto out;
291       }
292
293       select_printf ("woke up.  wait_ret %d.  verifying", wait_ret);
294       s = &start;
295       int gotone = FALSE;
296       while ((s = s->next))
297         if (s->saw_error)
298           return -1;            /* Somebody detected an error */
299         else if ((((wait_ret >= m && s->windows_handle) || s->h == w4[wait_ret])) &&
300             s->verify (s, readfds, writefds, exceptfds))
301           gotone = TRUE;
302
303       select_printf ("gotone %d", gotone);
304       if (gotone)
305         goto out;
306
307       if (ms == INFINITE)
308         {
309           select_printf ("looping");
310           continue;
311         }
312       select_printf ("recalculating ms");
313
314       DWORD now = GetTickCount ();
315       if (now > (start_time + ms))
316         {
317           select_printf ("timed out after verification");
318           goto out;
319         }
320       ms -= (now - start_time);
321       start_time = now;
322       select_printf ("ms now %u", ms);
323     }
324
325 out:
326   select_printf ("returning 0");
327   return 0;
328 }
329
330 static int
331 set_bits (select_record *me, fd_set *readfds, fd_set *writefds,
332            fd_set *exceptfds)
333 {
334   int ready = 0;
335   select_printf ("me %p, testing fd %d (%s)", me, me->fd, me->fh->get_name ());
336   if (me->read_selected && me->read_ready)
337     {
338       UNIX_FD_SET (me->fd, readfds);
339       ready++;
340     }
341   if (me->write_selected && me->write_ready)
342     {
343       UNIX_FD_SET (me->fd, writefds);
344       ready++;
345     }
346   if (me->except_ready && me->except_ready)
347     {
348       UNIX_FD_SET (me->fd, exceptfds);
349       ready++;
350     }
351   select_printf ("ready %d", ready);
352   return ready;
353 }
354
355 static int
356 verify_true (select_record *, fd_set *, fd_set *, fd_set *)
357 {
358   return 1;
359 }
360
361 static int
362 verify_ok (select_record *me, fd_set *readfds, fd_set *writefds,
363            fd_set *exceptfds)
364 {
365   return set_bits (me, readfds, writefds, exceptfds);
366 }
367
368 static int
369 no_startup (select_record *, select_stuff *)
370 {
371   return 1;
372 }
373
374 static int
375 no_verify (select_record *, fd_set *, fd_set *, fd_set *)
376 {
377   return 0;
378 }
379
380 static int
381 peek_pipe (select_record *s, int ignra)
382 {
383   int n = 0;
384   int gotone = 0;
385   fhandler_base *fh = s->fh;
386
387   HANDLE h;
388   set_handle_or_return_if_not_open (h, s);
389
390   /* Don't perform complicated tests if we don't need to. */
391   if (!s->read_selected && !s->except_selected)
392     goto out;
393
394   if (s->read_selected)
395     {
396       if (s->read_ready)
397         {
398           select_printf ("already ready");
399           gotone = 1;
400           goto out;
401         }
402       if (fh->bg_check (SIGTTIN) <= 0)
403         {
404           gotone = s->read_ready = 1;
405           goto out;
406         }
407
408       if (!ignra && fh->get_device () != FH_PTYM && fh->get_device () != FH_TTYM &&
409           fh->get_readahead_valid ())
410         {
411           select_printf ("readahead");
412           gotone = s->read_ready = 1;
413           goto out;
414         }
415     }
416
417   if (fh->get_device() != FH_PIPEW &&
418       !PeekNamedPipe (h, NULL, 0, NULL, (DWORD *) &n, NULL))
419     {
420       select_printf ("%s, PeekNamedPipe failed, %E", fh->get_name ());
421       n = -1;
422     }
423
424   if (n < 0)
425     {
426       select_printf ("%s, n %d", fh->get_name (), n);
427       if (s->except_selected)
428         gotone += s->except_ready = TRUE;
429       if (s->read_selected)
430         gotone += s->read_ready = TRUE;
431     }
432   if (n > 0 && s->read_selected)
433     {
434       select_printf ("%s, ready for read", fh->get_name ());
435       gotone += s->read_ready = TRUE;
436     }
437   if (!gotone && s->fh->hit_eof ())
438     {
439       select_printf ("%s, saw EOF", fh->get_name ());
440       if (s->except_selected)
441         gotone = s->except_ready = TRUE;
442       if (s->read_selected)
443         gotone += s->read_ready = TRUE;
444       select_printf ("saw eof on '%s'", fh->get_name ());
445     }
446
447 out:
448   return gotone || s->write_ready;
449 }
450
451 static int
452 poll_pipe (select_record *me, fd_set *readfds, fd_set *writefds,
453            fd_set *exceptfds)
454 {
455   return peek_pipe (me, 0) ?
456          set_bits (me, readfds, writefds, exceptfds) :
457          0;
458 }
459
460 MAKEready(pipe)
461
462 static int start_thread_pipe (select_record *me, select_stuff *stuff);
463
464 struct pipeinf
465   {
466     HANDLE thread;
467     BOOL stop_thread_pipe;
468     select_record *start;
469   };
470
471 static DWORD WINAPI
472 thread_pipe (void *arg)
473 {
474   pipeinf *pi = (pipeinf *)arg;
475   BOOL gotone = FALSE;
476
477   for (;;)
478     {
479       select_record *s = pi->start;
480       while ((s = s->next))
481         if (s->startup == start_thread_pipe)
482           {
483             if (peek_pipe (s, 0))
484               gotone = TRUE;
485             if (pi->stop_thread_pipe)
486               {
487                 select_printf ("stopping");
488                 goto out;
489               }
490           }
491       /* Paranoid check */
492       if (pi->stop_thread_pipe)
493         {
494           select_printf ("stopping from outer loop");
495           break;
496         }
497       if (gotone)
498         break;
499       Sleep (10);
500     }
501 out:
502   return 0;
503 }
504
505 static int
506 start_thread_pipe (select_record *me, select_stuff *stuff)
507 {
508   if (stuff->device_specific[FHDEVN(FH_PIPE)])
509     {
510       me->h = ((pipeinf *) stuff->device_specific[FHDEVN(FH_PIPE)])->thread;
511       return 1;
512     }
513   pipeinf *pi = new pipeinf;
514   pi->start = &stuff->start;
515   pi->stop_thread_pipe = FALSE;
516   pi->thread = me->h = makethread (thread_pipe, (LPVOID)pi, 0, "select_pipe");
517   if (!me->h)
518     return 0;
519   stuff->device_specific[FHDEVN(FH_PIPE)] = (void *)pi;
520   return 1;
521 }
522
523 static void
524 pipe_cleanup (select_record *, select_stuff *stuff)
525 {
526   pipeinf *pi = (pipeinf *)stuff->device_specific[FHDEVN(FH_PIPE)];
527   if (pi && pi->thread)
528     {
529       pi->stop_thread_pipe = TRUE;
530       WaitForSingleObject (pi->thread, INFINITE);
531       CloseHandle (pi->thread);
532       delete pi;
533       stuff->device_specific[FHDEVN(FH_PIPE)] = NULL;
534     }
535 }
536
537 select_record *
538 fhandler_pipe::select_read (select_record *s)
539 {
540   if (!s)
541     s = new select_record;
542   s->startup = start_thread_pipe;
543   s->poll = poll_pipe;
544   s->verify = verify_ok;
545   s->read_selected = TRUE;
546   s->cleanup = pipe_cleanup;
547   return s;
548 }
549
550 select_record *
551 fhandler_pipe::select_write (select_record *s)
552 {
553   if (!s)
554     {
555       s = new select_record;
556       s->startup = no_startup;
557       s->poll = poll_pipe;
558       s->verify = no_verify;
559     }
560   s->write_selected = TRUE;
561   s->write_ready = TRUE;
562   return s;
563 }
564
565 select_record *
566 fhandler_pipe::select_except (select_record *s)
567 {
568   if (!s)
569       s = new select_record;
570   s->startup = start_thread_pipe;
571   s->poll = poll_pipe;
572   s->verify = verify_ok;
573   s->cleanup = pipe_cleanup;
574   s->except_selected = TRUE;
575   return s;
576 }
577
578 static int
579 peek_console (select_record *me, int ignra)
580 {
581   extern const char * get_nonascii_key (INPUT_RECORD& input_rec, char *);
582   fhandler_console *fh = (fhandler_console *)me->fh;
583
584   if (!me->read_selected)
585     return me->write_ready;
586
587   if (!ignra && fh->get_readahead_valid ())
588     {
589       select_printf ("readahead");
590       return me->read_ready = 1;
591     }
592
593   if (me->read_ready)
594     {
595       select_printf ("already ready");
596       return 1;
597     }
598
599   INPUT_RECORD irec;
600   DWORD events_read;
601   HANDLE h;
602   char tmpbuf[17];
603   set_handle_or_return_if_not_open (h, me);
604
605   for (;;)
606     if (fh->bg_check (SIGTTIN) <= 0)
607       return me->read_ready = 1;
608     else if (!PeekConsoleInput (h, &irec, 1, &events_read) || !events_read)
609       break;
610     else
611       {
612         if (irec.EventType == WINDOW_BUFFER_SIZE_EVENT)
613           kill_pgrp (fh->tc->getpgid (), SIGWINCH);
614         else if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown == TRUE &&
615                  (irec.Event.KeyEvent.uChar.AsciiChar || get_nonascii_key (irec, tmpbuf)))
616           return me->read_ready = 1;
617
618         /* Read and discard the event */
619         ReadConsoleInput (h, &irec, 1, &events_read);
620       }
621
622   return me->write_ready;
623 }
624
625 static int
626 poll_console (select_record *me, fd_set *readfds, fd_set *writefds,
627               fd_set *exceptfds)
628 {
629   return peek_console (me, 0) ?
630          set_bits (me, readfds, writefds, exceptfds) :
631          0;
632 }
633
634 MAKEready (console)
635
636 select_record *
637 fhandler_console::select_read (select_record *s)
638 {
639   if (!s)
640     {
641       s = new select_record;
642       s->startup = no_startup;
643       s->poll = poll_console;
644       s->verify = poll_console;
645       set_cursor_maybe ();
646     }
647
648   s->h = get_handle ();
649   s->read_selected = TRUE;
650   return s;
651 }
652
653 select_record *
654 fhandler_console::select_write (select_record *s)
655 {
656   if (!s)
657     {
658       s = new select_record;
659       s->startup = no_startup;
660       s->poll = poll_console;
661       s->verify = no_verify;
662       set_cursor_maybe ();
663     }
664
665   s->write_selected = TRUE;
666   s->write_ready = TRUE;
667   return s;
668 }
669
670 select_record *
671 fhandler_console::select_except (select_record *s)
672 {
673   if (!s)
674     {
675       s = new select_record;
676       s->startup = no_startup;
677       s->poll = poll_console;
678       s->verify = no_verify;
679       set_cursor_maybe ();
680     }
681
682   s->except_selected = TRUE;
683   return s;
684 }
685
686 int
687 fhandler_tty_common::ready_for_read (int fd, DWORD howlong, int ignra)
688 {
689 #if 0
690   if (myself->pgid && get_ttyp ()->getpgid () != myself->pgid &&
691         myself->ctty == ttynum) // background process?
692     return 1;   // Yes. Let read return an error
693 #endif
694   return ((fhandler_pipe*)this)->fhandler_pipe::ready_for_read (fd, howlong, ignra);
695 }
696
697 select_record *
698 fhandler_tty_common::select_read (select_record *s)
699 {
700   return ((fhandler_pipe*)this)->fhandler_pipe::select_read (s);
701 }
702
703 select_record *
704 fhandler_tty_common::select_write (select_record *s)
705 {
706   return ((fhandler_pipe *)this)->fhandler_pipe::select_write (s);
707 }
708
709 select_record *
710 fhandler_tty_common::select_except (select_record *s)
711 {
712   return ((fhandler_pipe *)this)->fhandler_pipe::select_except (s);
713 }
714
715 select_record *
716 fhandler_dev_null::select_read (select_record *s)
717 {
718   if (!s)
719     {
720       s = new select_record;
721       s->startup = no_startup;
722       s->poll = set_bits;
723       s->verify = no_verify;
724     }
725   s->h = get_handle ();
726   s->read_selected = TRUE;
727   return s;
728 }
729
730 select_record *
731 fhandler_dev_null::select_write (select_record *s)
732 {
733   if (!s)
734     {
735       s = new select_record;
736       s->startup = no_startup;
737       s->poll = set_bits;
738       s->verify = no_verify;
739     }
740   s->h = get_handle ();
741   s->write_selected = TRUE;
742   return s;
743 }
744
745 select_record *
746 fhandler_dev_null::select_except (select_record *s)
747 {
748   if (!s)
749     {
750       s = new select_record;
751       s->startup = no_startup;
752       s->poll = set_bits;
753       s->verify = no_verify;
754     }
755   s->h = get_handle ();
756   s->except_selected = TRUE;
757   s->except_ready = TRUE;
758   return s;
759 }
760
761 static int start_thread_serial (select_record *me, select_stuff *stuff);
762
763 struct serialinf
764   {
765     HANDLE thread;
766     BOOL stop_thread_serial;
767     select_record *start;
768   };
769
770 static int
771 peek_serial (select_record *s, int)
772 {
773   DWORD ev;
774   COMSTAT st;
775
776   fhandler_serial *fh = (fhandler_serial *)s->fh;
777
778   if (fh->get_readahead_valid () || fh->overlapped_armed < 0)
779     return s->read_ready = 1;
780
781   select_printf ("fh->overlapped_armed %d", fh->overlapped_armed);
782
783   HANDLE h;
784   set_handle_or_return_if_not_open (h, s);
785   int ready = 0;
786
787   if (s->read_selected && s->read_ready || (s->write_selected && s->write_ready))
788     {
789       select_printf ("already ready");
790       ready = 1;
791       goto out;
792     }
793
794   (void) SetCommMask (h, EV_RXCHAR);
795
796   if (!fh->overlapped_armed)
797     {
798       DWORD ev;
799       COMSTAT st;
800
801       ResetEvent (fh->io_status.hEvent);
802
803       if (!ClearCommError (h, &ev, &st))
804         {
805           debug_printf ("ClearCommError");
806           goto err;
807         }
808       else if (st.cbInQue)
809         return s->read_ready = 1;
810       else if (WaitCommEvent (h, &ev, &fh->io_status))
811         return s->read_ready = 1;
812       else if (GetLastError () == ERROR_IO_PENDING)
813         fh->overlapped_armed = 1;
814       else
815         {
816           debug_printf ("WaitCommEvent");
817           goto err;
818         }
819     }
820
821   HANDLE w4[2];
822   DWORD to;
823
824   w4[0] = fh->io_status.hEvent;
825   w4[1] = signal_arrived;
826   to = 10;
827
828   switch (WaitForMultipleObjects (2, w4, FALSE, to))
829     {
830     case WAIT_OBJECT_0:
831       if (!ClearCommError (h, &ev, &st))
832         {
833           debug_printf ("ClearCommError");
834           goto err;
835         }
836       else if (!st.cbInQue)
837         Sleep (to);
838       else
839         {
840           return s->read_ready = 1;
841           select_printf ("got something");
842         }
843       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
844       break;
845     case WAIT_OBJECT_0 + 1:
846       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
847       select_printf ("interrupt");
848       set_sig_errno (EINTR);
849       ready = -1;
850       break;
851     case WAIT_TIMEOUT:
852       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
853       break;
854     default:
855       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
856       debug_printf ("WaitForMultipleObjects");
857       goto err;
858     }
859
860 out:
861   return ready;
862
863 err:
864   if (GetLastError () == ERROR_OPERATION_ABORTED)
865     {
866       select_printf ("operation aborted");
867       return ready;
868     }
869
870   __seterrno ();
871   s->saw_error = TRUE;
872   select_printf ("error %E");
873   return -1;
874 }
875
876 static DWORD WINAPI
877 thread_serial (void *arg)
878 {
879   serialinf *si = (serialinf *)arg;
880   BOOL gotone= FALSE;
881
882   for (;;)
883     {
884       select_record *s = si->start;
885       while ((s = s->next))
886         if (s->startup == start_thread_serial)
887           {
888             if (peek_serial (s, 0))
889               gotone = TRUE;
890           }
891       if (si->stop_thread_serial)
892         {
893           select_printf ("stopping");
894           break;
895         }
896       if (gotone)
897         break;
898     }
899
900   select_printf ("exiting");
901   return 0;
902 }
903
904 static int
905 start_thread_serial (select_record *me, select_stuff *stuff)
906 {
907   if (stuff->device_specific[FHDEVN(FH_SERIAL)])
908     {
909       me->h = ((pipeinf *) stuff->device_specific[FHDEVN(FH_SERIAL)])->thread;
910       return 1;
911     }
912   serialinf *si = new serialinf;
913   si->start = &stuff->start;
914   si->stop_thread_serial = FALSE;
915   si->thread = me->h = makethread (thread_serial, (LPVOID)si, 0, "select_serial");
916   if (!me->h)
917     return 0;
918   stuff->device_specific[FHDEVN(FH_SERIAL)] = (void *)si;
919   return 1;
920 }
921
922 static void
923 serial_cleanup (select_record *, select_stuff *stuff)
924 {
925   serialinf *si = (serialinf *)stuff->device_specific[FHDEVN(FH_SERIAL)];
926   if (si && si->thread)
927     {
928       si->stop_thread_serial = TRUE;
929       WaitForSingleObject (si->thread, INFINITE);
930       CloseHandle (si->thread);
931       delete si;
932       stuff->device_specific[FHDEVN(FH_SERIAL)] = NULL;
933     }
934 }
935
936 static int
937 poll_serial (select_record *me, fd_set *readfds, fd_set *writefds,
938            fd_set *exceptfds)
939
940 {
941   return peek_serial (me, 0) ?
942          set_bits (me, readfds, writefds, exceptfds) :
943          0;
944 }
945
946 MAKEready (serial)
947
948 select_record *
949 fhandler_serial::select_read (select_record *s)
950 {
951   if (!s)
952     {
953       s = new select_record;
954       s->startup = start_thread_serial;
955       s->poll = poll_serial;
956       s->verify = verify_ok;
957       s->cleanup = serial_cleanup;
958     }
959   s->read_selected = TRUE;
960   return s;
961 }
962
963 select_record *
964 fhandler_serial::select_write (select_record *s)
965 {
966   if (!s)
967     {
968       s = new select_record;
969       s->startup = no_startup;
970       s->poll = set_bits;
971       s->verify = verify_ok;
972     }
973   s->h = get_handle ();
974   s->write_selected = TRUE;
975   s->write_ready = TRUE;
976   return s;
977 }
978
979 select_record *
980 fhandler_serial::select_except (select_record *s)
981 {
982   if (!s)
983     {
984       s = new select_record;
985       s->startup = no_startup;
986       s->poll = set_bits;
987       s->verify = verify_ok;
988     }
989   s->h = NULL;
990   s->except_selected = FALSE;   // Can't do this
991   return s;
992 }
993
994 int
995 fhandler_base::ready_for_read (int, DWORD, int)
996 {
997   return 1;
998 }
999
1000 select_record *
1001 fhandler_base::select_read (select_record *s)
1002 {
1003   if (!s)
1004     {
1005       s = new select_record;
1006       s->startup = no_startup;
1007       s->poll = set_bits;
1008       s->verify = verify_ok;
1009     }
1010   s->h = get_handle ();
1011   s->read_selected = TRUE;
1012   s->read_ready = TRUE;
1013   return s;
1014 }
1015
1016 select_record *
1017 fhandler_base::select_write (select_record *s)
1018 {
1019   if (!s)
1020     {
1021       s = new select_record;
1022       s->startup = no_startup;
1023       s->poll = set_bits;
1024       s->verify = verify_ok;
1025     }
1026   s->h = get_handle ();
1027   s->write_selected = TRUE;
1028   s->write_ready = TRUE;
1029   return s;
1030 }
1031
1032 select_record *
1033 fhandler_base::select_except (select_record *s)
1034 {
1035   if (!s)
1036     {
1037       s = new select_record;
1038       s->startup = no_startup;
1039       s->poll = set_bits;
1040       s->verify = verify_ok;
1041     }
1042   s->h = NULL;
1043   s->write_selected = TRUE;
1044   return s;
1045 }
1046
1047 struct socketinf
1048   {
1049     HANDLE thread;
1050     winsock_fd_set readfds, writefds, exceptfds;
1051     SOCKET exitsock;
1052     struct sockaddr_in sin;
1053     select_record *start;
1054   };
1055
1056 static int
1057 peek_socket (select_record *me, int)
1058 {
1059   winsock_fd_set ws_readfds, ws_writefds, ws_exceptfds;
1060   struct timeval tv = {0, 0};
1061   WINSOCK_FD_ZERO (&ws_readfds);
1062   WINSOCK_FD_ZERO (&ws_writefds);
1063   WINSOCK_FD_ZERO (&ws_exceptfds);
1064   int gotone = 0;
1065
1066   HANDLE h;
1067   set_handle_or_return_if_not_open (h, me);
1068   select_printf ("considering handle %p", h);
1069
1070   if (me->read_selected)
1071     {
1072       select_printf ("adding read fd_set %s, fd %d", me->fh->get_name (),
1073                      me->fd);
1074       WINSOCK_FD_SET (h, &ws_readfds);
1075     }
1076   if (me->write_selected)
1077     {
1078       select_printf ("adding write fd_set %s, fd %d", me->fh->get_name (),
1079                      me->fd);
1080       WINSOCK_FD_SET (h, &ws_writefds);
1081     }
1082   if (me->except_selected)
1083     {
1084       select_printf ("adding except fd_set %s, fd %d", me->fh->get_name (),
1085                      me->fd);
1086       WINSOCK_FD_SET (h, &ws_exceptfds);
1087     }
1088   int r = WINSOCK_SELECT (0, &ws_readfds, &ws_writefds, &ws_exceptfds, &tv);
1089   select_printf ("WINSOCK_SELECT returned %d", r);
1090   if (r == -1)
1091     {
1092       select_printf ("error %d", WSAGetLastError ());
1093       return 0;
1094     }
1095
1096   if (WINSOCK_FD_ISSET (h, &ws_readfds) || (me->read_selected && me->read_ready))
1097     gotone = me->read_ready = TRUE;
1098   if (WINSOCK_FD_ISSET (h, &ws_writefds) || (me->write_selected && me->write_ready))
1099     gotone = me->write_ready = TRUE;
1100   if (WINSOCK_FD_ISSET (h, &ws_exceptfds) || (me->except_selected && me->except_ready))
1101     gotone = me->except_ready = TRUE;
1102   return gotone;
1103 }
1104
1105 static int
1106 poll_socket (select_record *me, fd_set *readfds, fd_set *writefds,
1107            fd_set *exceptfds)
1108 {
1109   return peek_socket (me, 0) ?
1110          set_bits (me, readfds, writefds, exceptfds) :
1111          0;
1112 }
1113
1114 MAKEready (socket)
1115
1116 static int start_thread_socket (select_record *, select_stuff *);
1117
1118 static DWORD WINAPI
1119 thread_socket (void *arg)
1120 {
1121   socketinf *si = (socketinf *)arg;
1122
1123   select_printf ("stuff_start %p", &si->start);
1124   int r = WINSOCK_SELECT (0, &si->readfds, &si->writefds, &si->exceptfds, NULL);
1125   select_printf ("Win32 select returned %d", r);
1126   if (r == -1)
1127     select_printf ("error %d", WSAGetLastError ());
1128   select_record *s = si->start;
1129   while ((s = s->next))
1130     if (s->startup == start_thread_socket)
1131         {
1132           HANDLE h = s->fh->get_handle ();
1133           select_printf ("s %p, testing fd %d (%s)", s, s->fd, s->fh->get_name ());
1134           if (WINSOCK_FD_ISSET (h, &si->readfds))
1135             {
1136               select_printf ("read_ready");
1137               s->read_ready = TRUE;
1138             }
1139           if (WINSOCK_FD_ISSET (h, &si->writefds))
1140             {
1141               select_printf ("write_ready");
1142               s->write_ready = TRUE;
1143             }
1144           if (WINSOCK_FD_ISSET (h, &si->exceptfds))
1145             {
1146               select_printf ("except_ready");
1147               s->except_ready = TRUE;
1148             }
1149         }
1150
1151   if (WINSOCK_FD_ISSET (si->exitsock, &si->readfds))
1152     select_printf ("saw exitsock read");
1153
1154   return 0;
1155 }
1156
1157 extern "C" unsigned long htonl (unsigned long);
1158
1159 static int
1160 start_thread_socket (select_record *me, select_stuff *stuff)
1161 {
1162   socketinf *si;
1163
1164   if ((si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)]))
1165     {
1166       me->h = si->thread;
1167       return 1;
1168     }
1169
1170   si = new socketinf;
1171   WINSOCK_FD_ZERO (&si->readfds);
1172   WINSOCK_FD_ZERO (&si->writefds);
1173   WINSOCK_FD_ZERO (&si->exceptfds);
1174   select_record *s = &stuff->start;
1175   while ((s = s->next))
1176     if (s->startup == start_thread_socket)
1177       {
1178         HANDLE h = s->fh->get_handle ();
1179         select_printf ("Handle %p", h);
1180         if (s->read_selected)
1181           {
1182             WINSOCK_FD_SET (h, &si->readfds);
1183             select_printf ("Added to readfds");
1184           }
1185         if (s->write_selected)
1186           {
1187             WINSOCK_FD_SET (h, &si->writefds);
1188             select_printf ("Added to writefds");
1189           }
1190         if (s->except_selected)
1191           {
1192             WINSOCK_FD_SET (h, &si->exceptfds);
1193             select_printf ("Added to exceptfds");
1194           }
1195       }
1196
1197   if ((si->exitsock = socket (PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
1198     {
1199       set_winsock_errno ();
1200       select_printf ("cannot create socket, %E");
1201       return -1;
1202     }
1203   /* Allow rapid reuse of the port. */
1204   int tmp = 1;
1205   (void) setsockopt (si->exitsock, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp, sizeof (tmp));
1206
1207   int sin_len = sizeof(si->sin);
1208   memset (&si->sin, 0, sizeof (si->sin));
1209   si->sin.sin_family = AF_INET;
1210   si->sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1211   if (bind (si->exitsock, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1212     {
1213       select_printf ("cannot bind socket, %E");
1214       goto err;
1215     }
1216
1217   if (getsockname (si->exitsock, (struct sockaddr *) &si->sin, &sin_len) < 0)
1218     {
1219       select_printf ("getsockname error");
1220       goto err;
1221     }
1222
1223   if (listen (si->exitsock, 1))
1224     {
1225       select_printf ("listen failed, %E");
1226       goto err;
1227     }
1228
1229   select_printf ("exitsock %p", si->exitsock);
1230   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->readfds);
1231   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->exceptfds);
1232   stuff->device_specific[FHDEVN(FH_SOCKET)] = (void *) si;
1233   si->start = &stuff->start;
1234   select_printf ("stuff_start %p", &stuff->start);
1235   si->thread = me->h = makethread (thread_socket, (LPVOID)si, 0,
1236                                   "select_socket");
1237   return !!me->h;
1238
1239 err:
1240   set_winsock_errno ();
1241   closesocket (si->exitsock);
1242   return -1;
1243 }
1244
1245 void
1246 socket_cleanup (select_record *, select_stuff *stuff)
1247 {
1248   socketinf *si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)];
1249   select_printf ("si %p si->thread %p", si, si ? si->thread : NULL);
1250   if (si && si->thread)
1251     {
1252       select_printf ("connection to si->exitsock %p", si->exitsock);
1253       SOCKET s = socket (AF_INET, SOCK_STREAM, 0);
1254       /* Connecting to si->exitsock will cause any executing select to wake
1255          up.  When this happens then the exitsock condition will cause the
1256          thread to terminate. */
1257       if (connect (s, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1258         {
1259           set_winsock_errno ();
1260           select_printf ("connect failed");
1261           /* FIXME: now what? */
1262         }
1263       shutdown (s, 2);
1264       closesocket (s);
1265
1266       /* Wait for thread to go away */
1267       WaitForSingleObject (si->thread, INFINITE);
1268       shutdown (si->exitsock, 2);
1269       closesocket (si->exitsock);
1270       CloseHandle (si->thread);
1271       stuff->device_specific[FHDEVN(FH_SOCKET)] = NULL;
1272       delete si;
1273     }
1274   select_printf ("returning");
1275 }
1276
1277 select_record *
1278 fhandler_socket::select_read (select_record *s)
1279 {
1280   if (!s)
1281     {
1282       s = new select_record;
1283       s->startup = start_thread_socket;
1284       s->poll = poll_socket;
1285       s->verify = verify_true;
1286       s->cleanup = socket_cleanup;
1287     }
1288   s->read_selected = TRUE;
1289   return s;
1290 }
1291
1292 select_record *
1293 fhandler_socket::select_write (select_record *s)
1294 {
1295   if (!s)
1296     {
1297       s = new select_record;
1298       s->startup = start_thread_socket;
1299       s->poll = poll_socket;
1300       s->verify = verify_true;
1301       s->cleanup = socket_cleanup;
1302     }
1303   s->write_selected = TRUE;
1304   return s;
1305 }
1306
1307 select_record *
1308 fhandler_socket::select_except (select_record *s)
1309 {
1310   if (!s)
1311     {
1312       s = new select_record;
1313       s->startup = start_thread_socket;
1314       s->poll = poll_socket;
1315       s->verify = verify_true;
1316       s->cleanup = socket_cleanup;
1317     }
1318   s->except_selected = TRUE;
1319   return s;
1320 }
1321
1322 static int
1323 peek_windows (select_record *me, int)
1324 {
1325   MSG m;
1326   HANDLE h;
1327   set_handle_or_return_if_not_open (h, me);
1328
1329   if (me->read_selected && me->read_ready)
1330     return 1;
1331
1332   if (PeekMessage (&m, (HWND) h, 0, 0, PM_NOREMOVE))
1333     {
1334       me->read_ready = TRUE;
1335       select_printf ("window %d(%p) ready", me->fd, me->fh->get_handle ());
1336       return 1;
1337     }
1338
1339   select_printf ("window %d(%p) not ready", me->fd, me->fh->get_handle ());
1340   return me->write_ready;
1341 }
1342
1343 static int
1344 poll_windows (select_record *me, fd_set *readfds, fd_set *writefds,
1345               fd_set *exceptfds)
1346 {
1347
1348   return peek_windows (me, 0) ?
1349          set_bits (me, readfds, writefds, exceptfds) :
1350          0;
1351 }
1352
1353 MAKEready (windows)
1354
1355 select_record *
1356 fhandler_windows::select_read (select_record *s)
1357 {
1358   if (!s)
1359     {
1360       s = new select_record;
1361       s->startup = no_startup;
1362       s->poll = poll_windows;
1363       s->verify = poll_windows;
1364     }
1365   s->h = get_handle ();
1366   s->read_selected = TRUE;
1367   s->h = get_handle ();
1368   s->windows_handle = TRUE;
1369   return s;
1370 }
1371
1372 select_record *
1373 fhandler_windows::select_write (select_record *s)
1374 {
1375   if (!s)
1376     {
1377       s = new select_record;
1378       s->startup = no_startup;
1379       s->poll = set_bits;
1380       s->verify = verify_ok;
1381     }
1382   s->h = get_handle ();
1383   s->write_selected = TRUE;
1384   s->write_ready = TRUE;
1385   s->windows_handle = TRUE;
1386   return s;
1387 }
1388
1389 select_record *
1390 fhandler_windows::select_except (select_record *s)
1391 {
1392   if (!s)
1393     {
1394       s = new select_record;
1395       s->startup = no_startup;
1396       s->poll = set_bits;
1397       s->verify = verify_ok;
1398     }
1399   s->h = get_handle ();
1400   s->except_selected = TRUE;
1401   s->except_ready = TRUE;
1402   s->windows_handle = TRUE;
1403   return s;
1404 }