OSDN Git Service

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