OSDN Git Service

* winsup.h: Change strchr inline for strange gcc problem.
[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 (m > MAXIMUM_WAIT_OBJECTS)
254         {
255           set_errno (EINVAL);
256           return -1;
257         }
258       if (!s->startup (s, this))
259         {
260           __seterrno ();
261           return -1;
262         }
263       if (s->h == NULL)
264         continue;
265       for (int i = 1; i < m; i++)
266         if (w4[i] == s->h)
267           goto next_while;
268       w4[m++] = s->h;
269   next_while:
270       continue;
271     }
272
273   DWORD start_time = GetTickCount ();   /* Record the current time for later use. */
274
275   debug_printf ("m %d, ms %u", m, ms);
276   for (;;)
277     {
278       if (!windows_used)
279         wait_ret = WaitForMultipleObjects (m, w4, FALSE, ms);
280       else
281         wait_ret = MsgWaitForMultipleObjects (m, w4, FALSE, ms, QS_ALLINPUT);
282
283       switch (wait_ret)
284       {
285         case WAIT_OBJECT_0:
286           select_printf ("signal received");
287           set_sig_errno (EINTR);
288           return -1;
289         case WAIT_FAILED:
290           select_printf ("WaitForMultipleObjects failed");
291           __seterrno ();
292           return -1;
293         case WAIT_TIMEOUT:
294           select_printf ("timed out");
295           goto out;
296       }
297
298       select_printf ("woke up.  wait_ret %d.  verifying", wait_ret);
299       s = &start;
300       int gotone = FALSE;
301       while ((s = s->next))
302         if (s->saw_error)
303           return -1;            /* Somebody detected an error */
304         else if ((((wait_ret >= m && s->windows_handle) || s->h == w4[wait_ret])) &&
305             s->verify (s, readfds, writefds, exceptfds))
306           gotone = TRUE;
307
308       select_printf ("gotone %d", gotone);
309       if (gotone)
310         goto out;
311
312       if (ms == INFINITE)
313         {
314           select_printf ("looping");
315           continue;
316         }
317       select_printf ("recalculating ms");
318
319       DWORD now = GetTickCount ();
320       if (now > (start_time + ms))
321         {
322           select_printf ("timed out after verification");
323           goto out;
324         }
325       ms -= (now - start_time);
326       start_time = now;
327       select_printf ("ms now %u", ms);
328     }
329
330 out:
331   select_printf ("returning 0");
332   return 0;
333 }
334
335 static int
336 set_bits (select_record *me, fd_set *readfds, fd_set *writefds,
337            fd_set *exceptfds)
338 {
339   int ready = 0;
340   select_printf ("me %p, testing fd %d (%s)", me, me->fd, me->fh->get_name ());
341   if (me->read_selected && me->read_ready)
342     {
343       UNIX_FD_SET (me->fd, readfds);
344       ready++;
345     }
346   if (me->write_selected && me->write_ready)
347     {
348       UNIX_FD_SET (me->fd, writefds);
349       ready++;
350     }
351   if (me->except_ready && me->except_ready)
352     {
353       UNIX_FD_SET (me->fd, exceptfds);
354       ready++;
355     }
356   select_printf ("ready %d", ready);
357   return ready;
358 }
359
360 static int
361 verify_true (select_record *, fd_set *, fd_set *, fd_set *)
362 {
363   return 1;
364 }
365
366 static int
367 verify_ok (select_record *me, fd_set *readfds, fd_set *writefds,
368            fd_set *exceptfds)
369 {
370   return set_bits (me, readfds, writefds, exceptfds);
371 }
372
373 static int
374 no_startup (select_record *, select_stuff *)
375 {
376   return 1;
377 }
378
379 static int
380 no_verify (select_record *, fd_set *, fd_set *, fd_set *)
381 {
382   return 0;
383 }
384
385 static int
386 peek_pipe (select_record *s, int ignra)
387 {
388   int n = 0;
389   int gotone = 0;
390   fhandler_base *fh = s->fh;
391
392   HANDLE h;
393   set_handle_or_return_if_not_open (h, s);
394
395   /* Don't perform complicated tests if we don't need to. */
396   if (!s->read_selected && !s->except_selected)
397     goto out;
398
399   if (s->read_selected)
400     {
401       if (s->read_ready)
402         {
403           select_printf ("already ready");
404           gotone = 1;
405           goto out;
406         }
407       if (fh->bg_check (SIGTTIN) <= 0)
408         {
409           gotone = s->read_ready = 1;
410           goto out;
411         }
412
413       if (!ignra && fh->get_device () != FH_PTYM && fh->get_device () != FH_TTYM &&
414           fh->get_readahead_valid ())
415         {
416           select_printf ("readahead");
417           gotone = s->read_ready = 1;
418           goto out;
419         }
420     }
421
422   if (fh->get_device() != FH_PIPEW &&
423       !PeekNamedPipe (h, NULL, 0, NULL, (DWORD *) &n, NULL))
424     {
425       select_printf ("%s, PeekNamedPipe failed, %E", fh->get_name ());
426       n = -1;
427     }
428
429   if (n < 0)
430     {
431       select_printf ("%s, n %d", fh->get_name (), n);
432       if (s->except_selected)
433         gotone += s->except_ready = TRUE;
434       if (s->read_selected)
435         gotone += s->read_ready = TRUE;
436     }
437   if (n > 0 && s->read_selected)
438     {
439       select_printf ("%s, ready for read", fh->get_name ());
440       gotone += s->read_ready = TRUE;
441     }
442   if (!gotone && s->fh->hit_eof ())
443     {
444       select_printf ("%s, saw EOF", fh->get_name ());
445       if (s->except_selected)
446         gotone = s->except_ready = TRUE;
447       if (s->read_selected)
448         gotone += s->read_ready = TRUE;
449       select_printf ("saw eof on '%s'", fh->get_name ());
450     }
451
452 out:
453   return gotone || s->write_ready;
454 }
455
456 static int
457 poll_pipe (select_record *me, fd_set *readfds, fd_set *writefds,
458            fd_set *exceptfds)
459 {
460   return peek_pipe (me, 0) ?
461          set_bits (me, readfds, writefds, exceptfds) :
462          0;
463 }
464
465 MAKEready(pipe)
466
467 static int start_thread_pipe (select_record *me, select_stuff *stuff);
468
469 struct pipeinf
470   {
471     HANDLE thread;
472     BOOL stop_thread_pipe;
473     select_record *start;
474   };
475
476 static DWORD WINAPI
477 thread_pipe (void *arg)
478 {
479   pipeinf *pi = (pipeinf *)arg;
480   BOOL gotone = FALSE;
481
482   for (;;)
483     {
484       select_record *s = pi->start;
485       while ((s = s->next))
486         if (s->startup == start_thread_pipe)
487           {
488             if (peek_pipe (s, 0))
489               gotone = TRUE;
490             if (pi->stop_thread_pipe)
491               {
492                 select_printf ("stopping");
493                 goto out;
494               }
495           }
496       /* Paranoid check */
497       if (pi->stop_thread_pipe)
498         {
499           select_printf ("stopping from outer loop");
500           break;
501         }
502       if (gotone)
503         break;
504       Sleep (10);
505     }
506 out:
507   return 0;
508 }
509
510 static int
511 start_thread_pipe (select_record *me, select_stuff *stuff)
512 {
513   if (stuff->device_specific[FHDEVN(FH_PIPE)])
514     {
515       me->h = ((pipeinf *) stuff->device_specific[FHDEVN(FH_PIPE)])->thread;
516       return 1;
517     }
518   pipeinf *pi = new pipeinf;
519   pi->start = &stuff->start;
520   pi->stop_thread_pipe = FALSE;
521   pi->thread = me->h = makethread (thread_pipe, (LPVOID)pi, 0, "select_pipe");
522   if (!me->h)
523     return 0;
524   stuff->device_specific[FHDEVN(FH_PIPE)] = (void *)pi;
525   return 1;
526 }
527
528 static void
529 pipe_cleanup (select_record *, select_stuff *stuff)
530 {
531   pipeinf *pi = (pipeinf *)stuff->device_specific[FHDEVN(FH_PIPE)];
532   if (pi && pi->thread)
533     {
534       pi->stop_thread_pipe = TRUE;
535       WaitForSingleObject (pi->thread, INFINITE);
536       CloseHandle (pi->thread);
537       delete pi;
538       stuff->device_specific[FHDEVN(FH_PIPE)] = NULL;
539     }
540 }
541
542 select_record *
543 fhandler_pipe::select_read (select_record *s)
544 {
545   if (!s)
546     s = new select_record;
547   s->startup = start_thread_pipe;
548   s->poll = poll_pipe;
549   s->verify = verify_ok;
550   s->read_selected = TRUE;
551   s->cleanup = pipe_cleanup;
552   return s;
553 }
554
555 select_record *
556 fhandler_pipe::select_write (select_record *s)
557 {
558   if (!s)
559     {
560       s = new select_record;
561       s->startup = no_startup;
562       s->poll = poll_pipe;
563       s->verify = no_verify;
564     }
565   s->write_selected = TRUE;
566   s->write_ready = TRUE;
567   return s;
568 }
569
570 select_record *
571 fhandler_pipe::select_except (select_record *s)
572 {
573   if (!s)
574       s = new select_record;
575   s->startup = start_thread_pipe;
576   s->poll = poll_pipe;
577   s->verify = verify_ok;
578   s->cleanup = pipe_cleanup;
579   s->except_selected = TRUE;
580   return s;
581 }
582
583 static int
584 peek_console (select_record *me, int ignra)
585 {
586   extern const char * get_nonascii_key (INPUT_RECORD& input_rec, char *);
587   fhandler_console *fh = (fhandler_console *)me->fh;
588
589   if (!me->read_selected)
590     return me->write_ready;
591
592   if (!ignra && fh->get_readahead_valid ())
593     {
594       select_printf ("readahead");
595       return me->read_ready = 1;
596     }
597
598   if (me->read_ready)
599     {
600       select_printf ("already ready");
601       return 1;
602     }
603
604   INPUT_RECORD irec;
605   DWORD events_read;
606   HANDLE h;
607   char tmpbuf[17];
608   set_handle_or_return_if_not_open (h, me);
609
610   for (;;)
611     if (fh->bg_check (SIGTTIN) <= 0)
612       return me->read_ready = 1;
613     else if (!PeekConsoleInput (h, &irec, 1, &events_read) || !events_read)
614       break;
615     else
616       {
617         if (irec.EventType == WINDOW_BUFFER_SIZE_EVENT)
618           kill_pgrp (fh->tc->getpgid (), SIGWINCH);
619         else if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown == TRUE &&
620                  (irec.Event.KeyEvent.uChar.AsciiChar || get_nonascii_key (irec, tmpbuf)))
621           return me->read_ready = 1;
622
623         /* Read and discard the event */
624         ReadConsoleInput (h, &irec, 1, &events_read);
625       }
626
627   return me->write_ready;
628 }
629
630 static int
631 poll_console (select_record *me, fd_set *readfds, fd_set *writefds,
632               fd_set *exceptfds)
633 {
634   return peek_console (me, 0) ?
635          set_bits (me, readfds, writefds, exceptfds) :
636          0;
637 }
638
639 MAKEready (console)
640
641 select_record *
642 fhandler_console::select_read (select_record *s)
643 {
644   if (!s)
645     {
646       s = new select_record;
647       s->startup = no_startup;
648       s->poll = poll_console;
649       s->verify = poll_console;
650       set_cursor_maybe ();
651     }
652
653   s->h = get_handle ();
654   s->read_selected = TRUE;
655   return s;
656 }
657
658 select_record *
659 fhandler_console::select_write (select_record *s)
660 {
661   if (!s)
662     {
663       s = new select_record;
664       s->startup = no_startup;
665       s->poll = poll_console;
666       s->verify = no_verify;
667       set_cursor_maybe ();
668     }
669
670   s->write_selected = TRUE;
671   s->write_ready = TRUE;
672   return s;
673 }
674
675 select_record *
676 fhandler_console::select_except (select_record *s)
677 {
678   if (!s)
679     {
680       s = new select_record;
681       s->startup = no_startup;
682       s->poll = poll_console;
683       s->verify = no_verify;
684       set_cursor_maybe ();
685     }
686
687   s->except_selected = TRUE;
688   return s;
689 }
690
691 int
692 fhandler_tty_common::ready_for_read (int fd, DWORD howlong, int ignra)
693 {
694 #if 0
695   if (myself->pgid && get_ttyp ()->getpgid () != myself->pgid &&
696         myself->ctty == ttynum) // background process?
697     return 1;   // Yes. Let read return an error
698 #endif
699   return ((fhandler_pipe*)this)->fhandler_pipe::ready_for_read (fd, howlong, ignra);
700 }
701
702 select_record *
703 fhandler_tty_common::select_read (select_record *s)
704 {
705   return ((fhandler_pipe*)this)->fhandler_pipe::select_read (s);
706 }
707
708 select_record *
709 fhandler_tty_common::select_write (select_record *s)
710 {
711   return ((fhandler_pipe *)this)->fhandler_pipe::select_write (s);
712 }
713
714 select_record *
715 fhandler_tty_common::select_except (select_record *s)
716 {
717   return ((fhandler_pipe *)this)->fhandler_pipe::select_except (s);
718 }
719
720 select_record *
721 fhandler_dev_null::select_read (select_record *s)
722 {
723   if (!s)
724     {
725       s = new select_record;
726       s->startup = no_startup;
727       s->poll = set_bits;
728       s->verify = no_verify;
729     }
730   s->h = get_handle ();
731   s->read_selected = TRUE;
732   return s;
733 }
734
735 select_record *
736 fhandler_dev_null::select_write (select_record *s)
737 {
738   if (!s)
739     {
740       s = new select_record;
741       s->startup = no_startup;
742       s->poll = set_bits;
743       s->verify = no_verify;
744     }
745   s->h = get_handle ();
746   s->write_selected = TRUE;
747   return s;
748 }
749
750 select_record *
751 fhandler_dev_null::select_except (select_record *s)
752 {
753   if (!s)
754     {
755       s = new select_record;
756       s->startup = no_startup;
757       s->poll = set_bits;
758       s->verify = no_verify;
759     }
760   s->h = get_handle ();
761   s->except_selected = TRUE;
762   s->except_ready = TRUE;
763   return s;
764 }
765
766 static int start_thread_serial (select_record *me, select_stuff *stuff);
767
768 struct serialinf
769   {
770     HANDLE thread;
771     BOOL stop_thread_serial;
772     select_record *start;
773   };
774
775 static int
776 peek_serial (select_record *s, int)
777 {
778   DWORD ev;
779   COMSTAT st;
780
781   fhandler_serial *fh = (fhandler_serial *)s->fh;
782
783   if (fh->get_readahead_valid () || fh->overlapped_armed < 0)
784     return s->read_ready = 1;
785
786   select_printf ("fh->overlapped_armed %d", fh->overlapped_armed);
787
788   HANDLE h;
789   set_handle_or_return_if_not_open (h, s);
790   int ready = 0;
791
792   if (s->read_selected && s->read_ready || (s->write_selected && s->write_ready))
793     {
794       select_printf ("already ready");
795       ready = 1;
796       goto out;
797     }
798
799   (void) SetCommMask (h, EV_RXCHAR);
800
801   if (!fh->overlapped_armed)
802     {
803       DWORD ev;
804       COMSTAT st;
805
806       ResetEvent (fh->io_status.hEvent);
807
808       if (!ClearCommError (h, &ev, &st))
809         {
810           debug_printf ("ClearCommError");
811           goto err;
812         }
813       else if (st.cbInQue)
814         return s->read_ready = 1;
815       else if (WaitCommEvent (h, &ev, &fh->io_status))
816         return s->read_ready = 1;
817       else if (GetLastError () == ERROR_IO_PENDING)
818         fh->overlapped_armed = 1;
819       else
820         {
821           debug_printf ("WaitCommEvent");
822           goto err;
823         }
824     }
825
826   HANDLE w4[2];
827   DWORD to;
828
829   w4[0] = fh->io_status.hEvent;
830   w4[1] = signal_arrived;
831   to = 10;
832
833   switch (WaitForMultipleObjects (2, w4, FALSE, to))
834     {
835     case WAIT_OBJECT_0:
836       if (!ClearCommError (h, &ev, &st))
837         {
838           debug_printf ("ClearCommError");
839           goto err;
840         }
841       else if (!st.cbInQue)
842         Sleep (to);
843       else
844         {
845           return s->read_ready = 1;
846           select_printf ("got something");
847         }
848       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
849       break;
850     case WAIT_OBJECT_0 + 1:
851       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
852       select_printf ("interrupt");
853       set_sig_errno (EINTR);
854       ready = -1;
855       break;
856     case WAIT_TIMEOUT:
857       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
858       break;
859     default:
860       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
861       debug_printf ("WaitForMultipleObjects");
862       goto err;
863     }
864
865 out:
866   return ready;
867
868 err:
869   if (GetLastError () == ERROR_OPERATION_ABORTED)
870     {
871       select_printf ("operation aborted");
872       return ready;
873     }
874
875   __seterrno ();
876   s->saw_error = TRUE;
877   select_printf ("error %E");
878   return -1;
879 }
880
881 static DWORD WINAPI
882 thread_serial (void *arg)
883 {
884   serialinf *si = (serialinf *)arg;
885   BOOL gotone= FALSE;
886
887   for (;;)
888     {
889       select_record *s = si->start;
890       while ((s = s->next))
891         if (s->startup == start_thread_serial)
892           {
893             if (peek_serial (s, 0))
894               gotone = TRUE;
895           }
896       if (si->stop_thread_serial)
897         {
898           select_printf ("stopping");
899           break;
900         }
901       if (gotone)
902         break;
903     }
904
905   select_printf ("exiting");
906   return 0;
907 }
908
909 static int
910 start_thread_serial (select_record *me, select_stuff *stuff)
911 {
912   if (stuff->device_specific[FHDEVN(FH_SERIAL)])
913     {
914       me->h = ((pipeinf *) stuff->device_specific[FHDEVN(FH_SERIAL)])->thread;
915       return 1;
916     }
917   serialinf *si = new serialinf;
918   si->start = &stuff->start;
919   si->stop_thread_serial = FALSE;
920   si->thread = me->h = makethread (thread_serial, (LPVOID)si, 0, "select_serial");
921   if (!me->h)
922     return 0;
923   stuff->device_specific[FHDEVN(FH_SERIAL)] = (void *)si;
924   return 1;
925 }
926
927 static void
928 serial_cleanup (select_record *, select_stuff *stuff)
929 {
930   serialinf *si = (serialinf *)stuff->device_specific[FHDEVN(FH_SERIAL)];
931   if (si && si->thread)
932     {
933       si->stop_thread_serial = TRUE;
934       WaitForSingleObject (si->thread, INFINITE);
935       CloseHandle (si->thread);
936       delete si;
937       stuff->device_specific[FHDEVN(FH_SERIAL)] = NULL;
938     }
939 }
940
941 static int
942 poll_serial (select_record *me, fd_set *readfds, fd_set *writefds,
943            fd_set *exceptfds)
944
945 {
946   return peek_serial (me, 0) ?
947          set_bits (me, readfds, writefds, exceptfds) :
948          0;
949 }
950
951 MAKEready (serial)
952
953 select_record *
954 fhandler_serial::select_read (select_record *s)
955 {
956   if (!s)
957     {
958       s = new select_record;
959       s->startup = start_thread_serial;
960       s->poll = poll_serial;
961       s->verify = verify_ok;
962       s->cleanup = serial_cleanup;
963     }
964   s->read_selected = TRUE;
965   return s;
966 }
967
968 select_record *
969 fhandler_serial::select_write (select_record *s)
970 {
971   if (!s)
972     {
973       s = new select_record;
974       s->startup = no_startup;
975       s->poll = set_bits;
976       s->verify = verify_ok;
977     }
978   s->h = get_handle ();
979   s->write_selected = TRUE;
980   s->write_ready = TRUE;
981   return s;
982 }
983
984 select_record *
985 fhandler_serial::select_except (select_record *s)
986 {
987   if (!s)
988     {
989       s = new select_record;
990       s->startup = no_startup;
991       s->poll = set_bits;
992       s->verify = verify_ok;
993     }
994   s->h = NULL;
995   s->except_selected = FALSE;   // Can't do this
996   return s;
997 }
998
999 int
1000 fhandler_base::ready_for_read (int, DWORD, int)
1001 {
1002   return 1;
1003 }
1004
1005 select_record *
1006 fhandler_base::select_read (select_record *s)
1007 {
1008   if (!s)
1009     {
1010       s = new select_record;
1011       s->startup = no_startup;
1012       s->poll = set_bits;
1013       s->verify = verify_ok;
1014     }
1015   s->h = get_handle ();
1016   s->read_selected = TRUE;
1017   s->read_ready = TRUE;
1018   return s;
1019 }
1020
1021 select_record *
1022 fhandler_base::select_write (select_record *s)
1023 {
1024   if (!s)
1025     {
1026       s = new select_record;
1027       s->startup = no_startup;
1028       s->poll = set_bits;
1029       s->verify = verify_ok;
1030     }
1031   s->h = get_handle ();
1032   s->write_selected = TRUE;
1033   s->write_ready = TRUE;
1034   return s;
1035 }
1036
1037 select_record *
1038 fhandler_base::select_except (select_record *s)
1039 {
1040   if (!s)
1041     {
1042       s = new select_record;
1043       s->startup = no_startup;
1044       s->poll = set_bits;
1045       s->verify = verify_ok;
1046     }
1047   s->h = NULL;
1048   s->write_selected = TRUE;
1049   return s;
1050 }
1051
1052 struct socketinf
1053   {
1054     HANDLE thread;
1055     winsock_fd_set readfds, writefds, exceptfds;
1056     SOCKET exitsock;
1057     struct sockaddr_in sin;
1058     select_record *start;
1059   };
1060
1061 static int
1062 peek_socket (select_record *me, int)
1063 {
1064   winsock_fd_set ws_readfds, ws_writefds, ws_exceptfds;
1065   struct timeval tv = {0, 0};
1066   WINSOCK_FD_ZERO (&ws_readfds);
1067   WINSOCK_FD_ZERO (&ws_writefds);
1068   WINSOCK_FD_ZERO (&ws_exceptfds);
1069   int gotone = 0;
1070
1071   HANDLE h;
1072   set_handle_or_return_if_not_open (h, me);
1073   select_printf ("considering handle %p", h);
1074
1075   if (me->read_selected)
1076     {
1077       select_printf ("adding read fd_set %s, fd %d", me->fh->get_name (),
1078                      me->fd);
1079       WINSOCK_FD_SET (h, &ws_readfds);
1080     }
1081   if (me->write_selected)
1082     {
1083       select_printf ("adding write fd_set %s, fd %d", me->fh->get_name (),
1084                      me->fd);
1085       WINSOCK_FD_SET (h, &ws_writefds);
1086     }
1087   if (me->except_selected)
1088     {
1089       select_printf ("adding except fd_set %s, fd %d", me->fh->get_name (),
1090                      me->fd);
1091       WINSOCK_FD_SET (h, &ws_exceptfds);
1092     }
1093   int r = WINSOCK_SELECT (0, &ws_readfds, &ws_writefds, &ws_exceptfds, &tv);
1094   select_printf ("WINSOCK_SELECT returned %d", r);
1095   if (r == -1)
1096     {
1097       select_printf ("error %d", WSAGetLastError ());
1098       return 0;
1099     }
1100
1101   if (WINSOCK_FD_ISSET (h, &ws_readfds) || (me->read_selected && me->read_ready))
1102     gotone = me->read_ready = TRUE;
1103   if (WINSOCK_FD_ISSET (h, &ws_writefds) || (me->write_selected && me->write_ready))
1104     gotone = me->write_ready = TRUE;
1105   if (WINSOCK_FD_ISSET (h, &ws_exceptfds) || (me->except_selected && me->except_ready))
1106     gotone = me->except_ready = TRUE;
1107   return gotone;
1108 }
1109
1110 static int
1111 poll_socket (select_record *me, fd_set *readfds, fd_set *writefds,
1112            fd_set *exceptfds)
1113 {
1114   return peek_socket (me, 0) ?
1115          set_bits (me, readfds, writefds, exceptfds) :
1116          0;
1117 }
1118
1119 MAKEready (socket)
1120
1121 static int start_thread_socket (select_record *, select_stuff *);
1122
1123 static DWORD WINAPI
1124 thread_socket (void *arg)
1125 {
1126   socketinf *si = (socketinf *)arg;
1127
1128   select_printf ("stuff_start %p", &si->start);
1129   int r = WINSOCK_SELECT (0, &si->readfds, &si->writefds, &si->exceptfds, NULL);
1130   select_printf ("Win32 select returned %d", r);
1131   if (r == -1)
1132     select_printf ("error %d", WSAGetLastError ());
1133   select_record *s = si->start;
1134   while ((s = s->next))
1135     if (s->startup == start_thread_socket)
1136         {
1137           HANDLE h = s->fh->get_handle ();
1138           select_printf ("s %p, testing fd %d (%s)", s, s->fd, s->fh->get_name ());
1139           if (WINSOCK_FD_ISSET (h, &si->readfds))
1140             {
1141               select_printf ("read_ready");
1142               s->read_ready = TRUE;
1143             }
1144           if (WINSOCK_FD_ISSET (h, &si->writefds))
1145             {
1146               select_printf ("write_ready");
1147               s->write_ready = TRUE;
1148             }
1149           if (WINSOCK_FD_ISSET (h, &si->exceptfds))
1150             {
1151               select_printf ("except_ready");
1152               s->except_ready = TRUE;
1153             }
1154         }
1155
1156   if (WINSOCK_FD_ISSET (si->exitsock, &si->readfds))
1157     select_printf ("saw exitsock read");
1158
1159   return 0;
1160 }
1161
1162 extern "C" unsigned long htonl (unsigned long);
1163
1164 static int
1165 start_thread_socket (select_record *me, select_stuff *stuff)
1166 {
1167   socketinf *si;
1168
1169   if ((si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)]))
1170     {
1171       me->h = si->thread;
1172       return 1;
1173     }
1174
1175   si = new socketinf;
1176   WINSOCK_FD_ZERO (&si->readfds);
1177   WINSOCK_FD_ZERO (&si->writefds);
1178   WINSOCK_FD_ZERO (&si->exceptfds);
1179   select_record *s = &stuff->start;
1180   while ((s = s->next))
1181     if (s->startup == start_thread_socket)
1182       {
1183         HANDLE h = s->fh->get_handle ();
1184         select_printf ("Handle %p", h);
1185         if (s->read_selected)
1186           {
1187             WINSOCK_FD_SET (h, &si->readfds);
1188             select_printf ("Added to readfds");
1189           }
1190         if (s->write_selected)
1191           {
1192             WINSOCK_FD_SET (h, &si->writefds);
1193             select_printf ("Added to writefds");
1194           }
1195         if (s->except_selected)
1196           {
1197             WINSOCK_FD_SET (h, &si->exceptfds);
1198             select_printf ("Added to exceptfds");
1199           }
1200       }
1201
1202   if ((si->exitsock = socket (PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
1203     {
1204       set_winsock_errno ();
1205       select_printf ("cannot create socket, %E");
1206       return -1;
1207     }
1208   /* Allow rapid reuse of the port. */
1209   int tmp = 1;
1210   (void) setsockopt (si->exitsock, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp, sizeof (tmp));
1211
1212   int sin_len = sizeof(si->sin);
1213   memset (&si->sin, 0, sizeof (si->sin));
1214   si->sin.sin_family = AF_INET;
1215   si->sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1216   if (bind (si->exitsock, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1217     {
1218       select_printf ("cannot bind socket, %E");
1219       goto err;
1220     }
1221
1222   if (getsockname (si->exitsock, (struct sockaddr *) &si->sin, &sin_len) < 0)
1223     {
1224       select_printf ("getsockname error");
1225       goto err;
1226     }
1227
1228   if (listen (si->exitsock, 1))
1229     {
1230       select_printf ("listen failed, %E");
1231       goto err;
1232     }
1233
1234   select_printf ("exitsock %p", si->exitsock);
1235   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->readfds);
1236   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->exceptfds);
1237   stuff->device_specific[FHDEVN(FH_SOCKET)] = (void *) si;
1238   si->start = &stuff->start;
1239   select_printf ("stuff_start %p", &stuff->start);
1240   si->thread = me->h = makethread (thread_socket, (LPVOID)si, 0,
1241                                   "select_socket");
1242   return !!me->h;
1243
1244 err:
1245   set_winsock_errno ();
1246   closesocket (si->exitsock);
1247   return -1;
1248 }
1249
1250 void
1251 socket_cleanup (select_record *, select_stuff *stuff)
1252 {
1253   socketinf *si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)];
1254   select_printf ("si %p si->thread %p", si, si ? si->thread : NULL);
1255   if (si && si->thread)
1256     {
1257       select_printf ("connection to si->exitsock %p", si->exitsock);
1258       SOCKET s = socket (AF_INET, SOCK_STREAM, 0);
1259       /* Connecting to si->exitsock will cause any executing select to wake
1260          up.  When this happens then the exitsock condition will cause the
1261          thread to terminate. */
1262       if (connect (s, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1263         {
1264           set_winsock_errno ();
1265           select_printf ("connect failed");
1266           /* FIXME: now what? */
1267         }
1268       shutdown (s, 2);
1269       closesocket (s);
1270
1271       /* Wait for thread to go away */
1272       WaitForSingleObject (si->thread, INFINITE);
1273       shutdown (si->exitsock, 2);
1274       closesocket (si->exitsock);
1275       CloseHandle (si->thread);
1276       stuff->device_specific[FHDEVN(FH_SOCKET)] = NULL;
1277       delete si;
1278     }
1279   select_printf ("returning");
1280 }
1281
1282 select_record *
1283 fhandler_socket::select_read (select_record *s)
1284 {
1285   if (!s)
1286     {
1287       s = new select_record;
1288       s->startup = start_thread_socket;
1289       s->poll = poll_socket;
1290       s->verify = verify_true;
1291       s->cleanup = socket_cleanup;
1292     }
1293   s->read_selected = TRUE;
1294   return s;
1295 }
1296
1297 select_record *
1298 fhandler_socket::select_write (select_record *s)
1299 {
1300   if (!s)
1301     {
1302       s = new select_record;
1303       s->startup = start_thread_socket;
1304       s->poll = poll_socket;
1305       s->verify = verify_true;
1306       s->cleanup = socket_cleanup;
1307     }
1308   s->write_selected = TRUE;
1309   return s;
1310 }
1311
1312 select_record *
1313 fhandler_socket::select_except (select_record *s)
1314 {
1315   if (!s)
1316     {
1317       s = new select_record;
1318       s->startup = start_thread_socket;
1319       s->poll = poll_socket;
1320       s->verify = verify_true;
1321       s->cleanup = socket_cleanup;
1322     }
1323   s->except_selected = TRUE;
1324   return s;
1325 }
1326
1327 static int
1328 peek_windows (select_record *me, int)
1329 {
1330   MSG m;
1331   HANDLE h;
1332   set_handle_or_return_if_not_open (h, me);
1333
1334   if (me->read_selected && me->read_ready)
1335     return 1;
1336
1337   if (PeekMessage (&m, (HWND) h, 0, 0, PM_NOREMOVE))
1338     {
1339       me->read_ready = TRUE;
1340       select_printf ("window %d(%p) ready", me->fd, me->fh->get_handle ());
1341       return 1;
1342     }
1343
1344   select_printf ("window %d(%p) not ready", me->fd, me->fh->get_handle ());
1345   return me->write_ready;
1346 }
1347
1348 static int
1349 poll_windows (select_record *me, fd_set *readfds, fd_set *writefds,
1350               fd_set *exceptfds)
1351 {
1352
1353   return peek_windows (me, 0) ?
1354          set_bits (me, readfds, writefds, exceptfds) :
1355          0;
1356 }
1357
1358 MAKEready (windows)
1359
1360 select_record *
1361 fhandler_windows::select_read (select_record *s)
1362 {
1363   if (!s)
1364     {
1365       s = new select_record;
1366       s->startup = no_startup;
1367       s->poll = poll_windows;
1368       s->verify = poll_windows;
1369     }
1370   s->h = get_handle ();
1371   s->read_selected = TRUE;
1372   s->h = get_handle ();
1373   s->windows_handle = TRUE;
1374   return s;
1375 }
1376
1377 select_record *
1378 fhandler_windows::select_write (select_record *s)
1379 {
1380   if (!s)
1381     {
1382       s = new select_record;
1383       s->startup = no_startup;
1384       s->poll = set_bits;
1385       s->verify = verify_ok;
1386     }
1387   s->h = get_handle ();
1388   s->write_selected = TRUE;
1389   s->write_ready = TRUE;
1390   s->windows_handle = TRUE;
1391   return s;
1392 }
1393
1394 select_record *
1395 fhandler_windows::select_except (select_record *s)
1396 {
1397   if (!s)
1398     {
1399       s = new select_record;
1400       s->startup = no_startup;
1401       s->poll = set_bits;
1402       s->verify = verify_ok;
1403     }
1404   s->h = get_handle ();
1405   s->except_selected = TRUE;
1406   s->except_ready = TRUE;
1407   s->windows_handle = TRUE;
1408   return s;
1409 }