OSDN Git Service

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