OSDN Git Service

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