OSDN Git Service

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