OSDN Git Service

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