OSDN Git Service

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