OSDN Git Service

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