OSDN Git Service

* select.cc (peek_pipe): Deal with pending newline in pty_master.
[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       switch (fh->get_device ())
422         {
423         case FH_PTYM:
424         case FH_TTYM:
425           if (((fhandler_pty_master *)fh)->need_nl)
426             {
427               gotone = s->read_ready = 1;
428               goto out;
429             }
430           break;
431         default:
432           if (!ignra && fh->get_readahead_valid ())
433             {
434               select_printf ("readahead");
435               gotone = s->read_ready = 1;
436               goto out;
437             }
438         }
439     }
440
441   if (fh->get_device() != FH_PIPEW &&
442       !PeekNamedPipe (h, NULL, 0, NULL, (DWORD *) &n, NULL))
443     {
444       select_printf ("%s, PeekNamedPipe failed, %E", fh->get_name ());
445       n = -1;
446     }
447
448   if (n < 0)
449     {
450       select_printf ("%s, n %d", fh->get_name (), n);
451       if (s->except_selected)
452         gotone += s->except_ready = TRUE;
453       if (s->read_selected)
454         gotone += s->read_ready = TRUE;
455     }
456   if (n > 0 && s->read_selected)
457     {
458       select_printf ("%s, ready for read", fh->get_name ());
459       gotone += s->read_ready = TRUE;
460     }
461   if (!gotone && s->fh->hit_eof ())
462     {
463       select_printf ("%s, saw EOF", fh->get_name ());
464       if (s->except_selected)
465         gotone = s->except_ready = TRUE;
466       if (s->read_selected)
467         gotone += s->read_ready = TRUE;
468       select_printf ("saw eof on '%s'", fh->get_name ());
469     }
470
471 out:
472   return gotone || s->write_ready;
473 }
474
475 static int
476 poll_pipe (select_record *me, fd_set *readfds, fd_set *writefds,
477            fd_set *exceptfds)
478 {
479   return peek_pipe (me, 0) ?
480          set_bits (me, readfds, writefds, exceptfds) :
481          0;
482 }
483
484 MAKEready(pipe)
485
486 static int start_thread_pipe (select_record *me, select_stuff *stuff);
487
488 struct pipeinf
489   {
490     HANDLE thread;
491     BOOL stop_thread_pipe;
492     select_record *start;
493   };
494
495 static DWORD WINAPI
496 thread_pipe (void *arg)
497 {
498   pipeinf *pi = (pipeinf *)arg;
499   BOOL gotone = FALSE;
500
501   for (;;)
502     {
503       select_record *s = pi->start;
504       while ((s = s->next))
505         if (s->startup == start_thread_pipe)
506           {
507             if (peek_pipe (s, 0))
508               gotone = TRUE;
509             if (pi->stop_thread_pipe)
510               {
511                 select_printf ("stopping");
512                 goto out;
513               }
514           }
515       /* Paranoid check */
516       if (pi->stop_thread_pipe)
517         {
518           select_printf ("stopping from outer loop");
519           break;
520         }
521       if (gotone)
522         break;
523       Sleep (10);
524     }
525 out:
526   return 0;
527 }
528
529 static int
530 start_thread_pipe (select_record *me, select_stuff *stuff)
531 {
532   if (stuff->device_specific[FHDEVN(FH_PIPE)])
533     {
534       me->h = ((pipeinf *) stuff->device_specific[FHDEVN(FH_PIPE)])->thread;
535       return 1;
536     }
537   pipeinf *pi = new pipeinf;
538   pi->start = &stuff->start;
539   pi->stop_thread_pipe = FALSE;
540   pi->thread = me->h = makethread (thread_pipe, (LPVOID)pi, 0, "select_pipe");
541   if (!me->h)
542     return 0;
543   stuff->device_specific[FHDEVN(FH_PIPE)] = (void *)pi;
544   return 1;
545 }
546
547 static void
548 pipe_cleanup (select_record *, select_stuff *stuff)
549 {
550   pipeinf *pi = (pipeinf *)stuff->device_specific[FHDEVN(FH_PIPE)];
551   if (pi && pi->thread)
552     {
553       pi->stop_thread_pipe = TRUE;
554       WaitForSingleObject (pi->thread, INFINITE);
555       CloseHandle (pi->thread);
556       delete pi;
557       stuff->device_specific[FHDEVN(FH_PIPE)] = NULL;
558     }
559 }
560
561 select_record *
562 fhandler_pipe::select_read (select_record *s)
563 {
564   if (!s)
565     s = new select_record;
566   s->startup = start_thread_pipe;
567   s->poll = poll_pipe;
568   s->verify = verify_ok;
569   s->read_selected = TRUE;
570   s->cleanup = pipe_cleanup;
571   return s;
572 }
573
574 select_record *
575 fhandler_pipe::select_write (select_record *s)
576 {
577   if (!s)
578     {
579       s = new select_record;
580       s->startup = no_startup;
581       s->poll = poll_pipe;
582       s->verify = no_verify;
583     }
584   s->write_selected = TRUE;
585   s->write_ready = TRUE;
586   return s;
587 }
588
589 select_record *
590 fhandler_pipe::select_except (select_record *s)
591 {
592   if (!s)
593       s = new select_record;
594   s->startup = start_thread_pipe;
595   s->poll = poll_pipe;
596   s->verify = verify_ok;
597   s->cleanup = pipe_cleanup;
598   s->except_selected = TRUE;
599   return s;
600 }
601
602 static int
603 peek_console (select_record *me, int ignra)
604 {
605   extern const char * get_nonascii_key (INPUT_RECORD& input_rec, char *);
606   fhandler_console *fh = (fhandler_console *)me->fh;
607
608   if (!me->read_selected)
609     return me->write_ready;
610
611   if (!ignra && fh->get_readahead_valid ())
612     {
613       select_printf ("readahead");
614       return me->read_ready = 1;
615     }
616
617   if (me->read_ready)
618     {
619       select_printf ("already ready");
620       return 1;
621     }
622
623   INPUT_RECORD irec;
624   DWORD events_read;
625   HANDLE h;
626   char tmpbuf[17];
627   set_handle_or_return_if_not_open (h, me);
628
629   for (;;)
630     if (fh->bg_check (SIGTTIN) <= 0)
631       return me->read_ready = 1;
632     else if (!PeekConsoleInput (h, &irec, 1, &events_read) || !events_read)
633       break;
634     else
635       {
636         if (irec.EventType == WINDOW_BUFFER_SIZE_EVENT)
637           kill_pgrp (fh->tc->getpgid (), SIGWINCH);
638         else if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown == TRUE &&
639                  (irec.Event.KeyEvent.uChar.AsciiChar || get_nonascii_key (irec, tmpbuf)))
640           return me->read_ready = 1;
641
642         /* Read and discard the event */
643         ReadConsoleInput (h, &irec, 1, &events_read);
644       }
645
646   return me->write_ready;
647 }
648
649 static int
650 poll_console (select_record *me, fd_set *readfds, fd_set *writefds,
651               fd_set *exceptfds)
652 {
653   return peek_console (me, 0) ?
654          set_bits (me, readfds, writefds, exceptfds) :
655          0;
656 }
657
658 MAKEready (console)
659
660 select_record *
661 fhandler_console::select_read (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 = poll_console;
669       set_cursor_maybe ();
670     }
671
672   s->h = get_handle ();
673   s->read_selected = TRUE;
674   return s;
675 }
676
677 select_record *
678 fhandler_console::select_write (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->write_selected = TRUE;
690   s->write_ready = TRUE;
691   return s;
692 }
693
694 select_record *
695 fhandler_console::select_except (select_record *s)
696 {
697   if (!s)
698     {
699       s = new select_record;
700       s->startup = no_startup;
701       s->poll = poll_console;
702       s->verify = no_verify;
703       set_cursor_maybe ();
704     }
705
706   s->except_selected = TRUE;
707   return s;
708 }
709
710 int
711 fhandler_tty_common::ready_for_read (int fd, DWORD howlong, int ignra)
712 {
713 #if 0
714   if (myself->pgid && get_ttyp ()->getpgid () != myself->pgid &&
715         myself->ctty == ttynum) // background process?
716     return 1;   // Yes. Let read return an error
717 #endif
718   return ((fhandler_pipe*)this)->fhandler_pipe::ready_for_read (fd, howlong, ignra);
719 }
720
721 select_record *
722 fhandler_tty_common::select_read (select_record *s)
723 {
724   return ((fhandler_pipe*)this)->fhandler_pipe::select_read (s);
725 }
726
727 select_record *
728 fhandler_tty_common::select_write (select_record *s)
729 {
730   return ((fhandler_pipe *)this)->fhandler_pipe::select_write (s);
731 }
732
733 select_record *
734 fhandler_tty_common::select_except (select_record *s)
735 {
736   return ((fhandler_pipe *)this)->fhandler_pipe::select_except (s);
737 }
738
739 select_record *
740 fhandler_dev_null::select_read (select_record *s)
741 {
742   if (!s)
743     {
744       s = new select_record;
745       s->startup = no_startup;
746       s->poll = set_bits;
747       s->verify = no_verify;
748     }
749   s->h = get_handle ();
750   s->read_selected = TRUE;
751   return s;
752 }
753
754 select_record *
755 fhandler_dev_null::select_write (select_record *s)
756 {
757   if (!s)
758     {
759       s = new select_record;
760       s->startup = no_startup;
761       s->poll = set_bits;
762       s->verify = no_verify;
763     }
764   s->h = get_handle ();
765   s->write_selected = TRUE;
766   return s;
767 }
768
769 select_record *
770 fhandler_dev_null::select_except (select_record *s)
771 {
772   if (!s)
773     {
774       s = new select_record;
775       s->startup = no_startup;
776       s->poll = set_bits;
777       s->verify = no_verify;
778     }
779   s->h = get_handle ();
780   s->except_selected = TRUE;
781   s->except_ready = TRUE;
782   return s;
783 }
784
785 static int start_thread_serial (select_record *me, select_stuff *stuff);
786
787 struct serialinf
788   {
789     HANDLE thread;
790     BOOL stop_thread_serial;
791     select_record *start;
792   };
793
794 static int
795 peek_serial (select_record *s, int)
796 {
797   DWORD ev;
798   COMSTAT st;
799
800   fhandler_serial *fh = (fhandler_serial *)s->fh;
801
802   if (fh->get_readahead_valid () || fh->overlapped_armed < 0)
803     return s->read_ready = 1;
804
805   select_printf ("fh->overlapped_armed %d", fh->overlapped_armed);
806
807   HANDLE h;
808   set_handle_or_return_if_not_open (h, s);
809   int ready = 0;
810
811   if (s->read_selected && s->read_ready || (s->write_selected && s->write_ready))
812     {
813       select_printf ("already ready");
814       ready = 1;
815       goto out;
816     }
817
818   (void) SetCommMask (h, EV_RXCHAR);
819
820   if (!fh->overlapped_armed)
821     {
822       DWORD ev;
823       COMSTAT st;
824
825       ResetEvent (fh->io_status.hEvent);
826
827       if (!ClearCommError (h, &ev, &st))
828         {
829           debug_printf ("ClearCommError");
830           goto err;
831         }
832       else if (st.cbInQue)
833         return s->read_ready = 1;
834       else if (WaitCommEvent (h, &ev, &fh->io_status))
835         return s->read_ready = 1;
836       else if (GetLastError () == ERROR_IO_PENDING)
837         fh->overlapped_armed = 1;
838       else
839         {
840           debug_printf ("WaitCommEvent");
841           goto err;
842         }
843     }
844
845   HANDLE w4[2];
846   DWORD to;
847
848   w4[0] = fh->io_status.hEvent;
849   w4[1] = signal_arrived;
850   to = 10;
851
852   switch (WaitForMultipleObjects (2, w4, FALSE, to))
853     {
854     case WAIT_OBJECT_0:
855       if (!ClearCommError (h, &ev, &st))
856         {
857           debug_printf ("ClearCommError");
858           goto err;
859         }
860       else if (!st.cbInQue)
861         Sleep (to);
862       else
863         {
864           return s->read_ready = 1;
865           select_printf ("got something");
866         }
867       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
868       break;
869     case WAIT_OBJECT_0 + 1:
870       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
871       select_printf ("interrupt");
872       set_sig_errno (EINTR);
873       ready = -1;
874       break;
875     case WAIT_TIMEOUT:
876       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
877       break;
878     default:
879       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
880       debug_printf ("WaitForMultipleObjects");
881       goto err;
882     }
883
884 out:
885   return ready;
886
887 err:
888   if (GetLastError () == ERROR_OPERATION_ABORTED)
889     {
890       select_printf ("operation aborted");
891       return ready;
892     }
893
894   __seterrno ();
895   s->saw_error = TRUE;
896   select_printf ("error %E");
897   return -1;
898 }
899
900 static DWORD WINAPI
901 thread_serial (void *arg)
902 {
903   serialinf *si = (serialinf *)arg;
904   BOOL gotone= FALSE;
905
906   for (;;)
907     {
908       select_record *s = si->start;
909       while ((s = s->next))
910         if (s->startup == start_thread_serial)
911           {
912             if (peek_serial (s, 0))
913               gotone = TRUE;
914           }
915       if (si->stop_thread_serial)
916         {
917           select_printf ("stopping");
918           break;
919         }
920       if (gotone)
921         break;
922     }
923
924   select_printf ("exiting");
925   return 0;
926 }
927
928 static int
929 start_thread_serial (select_record *me, select_stuff *stuff)
930 {
931   if (stuff->device_specific[FHDEVN(FH_SERIAL)])
932     {
933       me->h = ((pipeinf *) stuff->device_specific[FHDEVN(FH_SERIAL)])->thread;
934       return 1;
935     }
936   serialinf *si = new serialinf;
937   si->start = &stuff->start;
938   si->stop_thread_serial = FALSE;
939   si->thread = me->h = makethread (thread_serial, (LPVOID)si, 0, "select_serial");
940   if (!me->h)
941     return 0;
942   stuff->device_specific[FHDEVN(FH_SERIAL)] = (void *)si;
943   return 1;
944 }
945
946 static void
947 serial_cleanup (select_record *, select_stuff *stuff)
948 {
949   serialinf *si = (serialinf *)stuff->device_specific[FHDEVN(FH_SERIAL)];
950   if (si && si->thread)
951     {
952       si->stop_thread_serial = TRUE;
953       WaitForSingleObject (si->thread, INFINITE);
954       CloseHandle (si->thread);
955       delete si;
956       stuff->device_specific[FHDEVN(FH_SERIAL)] = NULL;
957     }
958 }
959
960 static int
961 poll_serial (select_record *me, fd_set *readfds, fd_set *writefds,
962            fd_set *exceptfds)
963
964 {
965   return peek_serial (me, 0) ?
966          set_bits (me, readfds, writefds, exceptfds) :
967          0;
968 }
969
970 MAKEready (serial)
971
972 select_record *
973 fhandler_serial::select_read (select_record *s)
974 {
975   if (!s)
976     {
977       s = new select_record;
978       s->startup = start_thread_serial;
979       s->poll = poll_serial;
980       s->verify = verify_ok;
981       s->cleanup = serial_cleanup;
982     }
983   s->read_selected = TRUE;
984   return s;
985 }
986
987 select_record *
988 fhandler_serial::select_write (select_record *s)
989 {
990   if (!s)
991     {
992       s = new select_record;
993       s->startup = no_startup;
994       s->poll = set_bits;
995       s->verify = verify_ok;
996     }
997   s->h = get_handle ();
998   s->write_selected = TRUE;
999   s->write_ready = TRUE;
1000   return s;
1001 }
1002
1003 select_record *
1004 fhandler_serial::select_except (select_record *s)
1005 {
1006   if (!s)
1007     {
1008       s = new select_record;
1009       s->startup = no_startup;
1010       s->poll = set_bits;
1011       s->verify = verify_ok;
1012     }
1013   s->h = NULL;
1014   s->except_selected = FALSE;   // Can't do this
1015   return s;
1016 }
1017
1018 int
1019 fhandler_base::ready_for_read (int, DWORD, int)
1020 {
1021   return 1;
1022 }
1023
1024 select_record *
1025 fhandler_base::select_read (select_record *s)
1026 {
1027   if (!s)
1028     {
1029       s = new select_record;
1030       s->startup = no_startup;
1031       s->poll = set_bits;
1032       s->verify = verify_ok;
1033     }
1034   s->h = get_handle ();
1035   s->read_selected = TRUE;
1036   s->read_ready = TRUE;
1037   return s;
1038 }
1039
1040 select_record *
1041 fhandler_base::select_write (select_record *s)
1042 {
1043   if (!s)
1044     {
1045       s = new select_record;
1046       s->startup = no_startup;
1047       s->poll = set_bits;
1048       s->verify = verify_ok;
1049     }
1050   s->h = get_handle ();
1051   s->write_selected = TRUE;
1052   s->write_ready = TRUE;
1053   return s;
1054 }
1055
1056 select_record *
1057 fhandler_base::select_except (select_record *s)
1058 {
1059   if (!s)
1060     {
1061       s = new select_record;
1062       s->startup = no_startup;
1063       s->poll = set_bits;
1064       s->verify = verify_ok;
1065     }
1066   s->h = NULL;
1067   s->write_selected = TRUE;
1068   return s;
1069 }
1070
1071 struct socketinf
1072   {
1073     HANDLE thread;
1074     winsock_fd_set readfds, writefds, exceptfds;
1075     SOCKET exitsock;
1076     struct sockaddr_in sin;
1077     select_record *start;
1078   };
1079
1080 static int
1081 peek_socket (select_record *me, int)
1082 {
1083   winsock_fd_set ws_readfds, ws_writefds, ws_exceptfds;
1084   struct timeval tv = {0, 0};
1085   WINSOCK_FD_ZERO (&ws_readfds);
1086   WINSOCK_FD_ZERO (&ws_writefds);
1087   WINSOCK_FD_ZERO (&ws_exceptfds);
1088   int gotone = 0;
1089
1090   HANDLE h;
1091   set_handle_or_return_if_not_open (h, me);
1092   select_printf ("considering handle %p", h);
1093
1094   if (me->read_selected)
1095     {
1096       select_printf ("adding read fd_set %s, fd %d", me->fh->get_name (),
1097                      me->fd);
1098       WINSOCK_FD_SET (h, &ws_readfds);
1099     }
1100   if (me->write_selected)
1101     {
1102       select_printf ("adding write fd_set %s, fd %d", me->fh->get_name (),
1103                      me->fd);
1104       WINSOCK_FD_SET (h, &ws_writefds);
1105     }
1106   if (me->except_selected)
1107     {
1108       select_printf ("adding except fd_set %s, fd %d", me->fh->get_name (),
1109                      me->fd);
1110       WINSOCK_FD_SET (h, &ws_exceptfds);
1111     }
1112   int r = WINSOCK_SELECT (0, &ws_readfds, &ws_writefds, &ws_exceptfds, &tv);
1113   select_printf ("WINSOCK_SELECT returned %d", r);
1114   if (r == -1)
1115     {
1116       select_printf ("error %d", WSAGetLastError ());
1117       return 0;
1118     }
1119
1120   if (WINSOCK_FD_ISSET (h, &ws_readfds) || (me->read_selected && me->read_ready))
1121     gotone = me->read_ready = TRUE;
1122   if (WINSOCK_FD_ISSET (h, &ws_writefds) || (me->write_selected && me->write_ready))
1123     gotone = me->write_ready = TRUE;
1124   if (WINSOCK_FD_ISSET (h, &ws_exceptfds) || (me->except_selected && me->except_ready))
1125     gotone = me->except_ready = TRUE;
1126   return gotone;
1127 }
1128
1129 static int
1130 poll_socket (select_record *me, fd_set *readfds, fd_set *writefds,
1131            fd_set *exceptfds)
1132 {
1133   return peek_socket (me, 0) ?
1134          set_bits (me, readfds, writefds, exceptfds) :
1135          0;
1136 }
1137
1138 MAKEready (socket)
1139
1140 static int start_thread_socket (select_record *, select_stuff *);
1141
1142 static DWORD WINAPI
1143 thread_socket (void *arg)
1144 {
1145   socketinf *si = (socketinf *)arg;
1146
1147   select_printf ("stuff_start %p", &si->start);
1148   int r = WINSOCK_SELECT (0, &si->readfds, &si->writefds, &si->exceptfds, NULL);
1149   select_printf ("Win32 select returned %d", r);
1150   if (r == -1)
1151     select_printf ("error %d", WSAGetLastError ());
1152   select_record *s = si->start;
1153   while ((s = s->next))
1154     if (s->startup == start_thread_socket)
1155         {
1156           HANDLE h = s->fh->get_handle ();
1157           select_printf ("s %p, testing fd %d (%s)", s, s->fd, s->fh->get_name ());
1158           if (WINSOCK_FD_ISSET (h, &si->readfds))
1159             {
1160               select_printf ("read_ready");
1161               s->read_ready = TRUE;
1162             }
1163           if (WINSOCK_FD_ISSET (h, &si->writefds))
1164             {
1165               select_printf ("write_ready");
1166               s->write_ready = TRUE;
1167             }
1168           if (WINSOCK_FD_ISSET (h, &si->exceptfds))
1169             {
1170               select_printf ("except_ready");
1171               s->except_ready = TRUE;
1172             }
1173         }
1174
1175   if (WINSOCK_FD_ISSET (si->exitsock, &si->readfds))
1176     select_printf ("saw exitsock read");
1177
1178   return 0;
1179 }
1180
1181 extern "C" unsigned long htonl (unsigned long);
1182
1183 static int
1184 start_thread_socket (select_record *me, select_stuff *stuff)
1185 {
1186   socketinf *si;
1187
1188   if ((si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)]))
1189     {
1190       me->h = si->thread;
1191       return 1;
1192     }
1193
1194   si = new socketinf;
1195   WINSOCK_FD_ZERO (&si->readfds);
1196   WINSOCK_FD_ZERO (&si->writefds);
1197   WINSOCK_FD_ZERO (&si->exceptfds);
1198   select_record *s = &stuff->start;
1199   while ((s = s->next))
1200     if (s->startup == start_thread_socket)
1201       {
1202         HANDLE h = s->fh->get_handle ();
1203         select_printf ("Handle %p", h);
1204         if (s->read_selected)
1205           {
1206             WINSOCK_FD_SET (h, &si->readfds);
1207             select_printf ("Added to readfds");
1208           }
1209         if (s->write_selected)
1210           {
1211             WINSOCK_FD_SET (h, &si->writefds);
1212             select_printf ("Added to writefds");
1213           }
1214         if (s->except_selected)
1215           {
1216             WINSOCK_FD_SET (h, &si->exceptfds);
1217             select_printf ("Added to exceptfds");
1218           }
1219       }
1220
1221   if ((si->exitsock = socket (PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
1222     {
1223       set_winsock_errno ();
1224       select_printf ("cannot create socket, %E");
1225       return -1;
1226     }
1227   /* Allow rapid reuse of the port. */
1228   int tmp = 1;
1229   (void) setsockopt (si->exitsock, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp, sizeof (tmp));
1230
1231   int sin_len = sizeof(si->sin);
1232   memset (&si->sin, 0, sizeof (si->sin));
1233   si->sin.sin_family = AF_INET;
1234   si->sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1235   if (bind (si->exitsock, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1236     {
1237       select_printf ("cannot bind socket, %E");
1238       goto err;
1239     }
1240
1241   if (getsockname (si->exitsock, (struct sockaddr *) &si->sin, &sin_len) < 0)
1242     {
1243       select_printf ("getsockname error");
1244       goto err;
1245     }
1246
1247   if (listen (si->exitsock, 1))
1248     {
1249       select_printf ("listen failed, %E");
1250       goto err;
1251     }
1252
1253   select_printf ("exitsock %p", si->exitsock);
1254   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->readfds);
1255   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->exceptfds);
1256   stuff->device_specific[FHDEVN(FH_SOCKET)] = (void *) si;
1257   si->start = &stuff->start;
1258   select_printf ("stuff_start %p", &stuff->start);
1259   si->thread = me->h = makethread (thread_socket, (LPVOID)si, 0,
1260                                   "select_socket");
1261   return !!me->h;
1262
1263 err:
1264   set_winsock_errno ();
1265   closesocket (si->exitsock);
1266   return -1;
1267 }
1268
1269 void
1270 socket_cleanup (select_record *, select_stuff *stuff)
1271 {
1272   socketinf *si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)];
1273   select_printf ("si %p si->thread %p", si, si ? si->thread : NULL);
1274   if (si && si->thread)
1275     {
1276       select_printf ("connection to si->exitsock %p", si->exitsock);
1277       SOCKET s = socket (AF_INET, SOCK_STREAM, 0);
1278       /* Connecting to si->exitsock will cause any executing select to wake
1279          up.  When this happens then the exitsock condition will cause the
1280          thread to terminate. */
1281       if (connect (s, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1282         {
1283           set_winsock_errno ();
1284           select_printf ("connect failed");
1285           /* FIXME: now what? */
1286         }
1287       shutdown (s, 2);
1288       closesocket (s);
1289
1290       /* Wait for thread to go away */
1291       WaitForSingleObject (si->thread, INFINITE);
1292       shutdown (si->exitsock, 2);
1293       closesocket (si->exitsock);
1294       CloseHandle (si->thread);
1295       stuff->device_specific[FHDEVN(FH_SOCKET)] = NULL;
1296       delete si;
1297     }
1298   select_printf ("returning");
1299 }
1300
1301 select_record *
1302 fhandler_socket::select_read (select_record *s)
1303 {
1304   if (!s)
1305     {
1306       s = new select_record;
1307       s->startup = start_thread_socket;
1308       s->poll = poll_socket;
1309       s->verify = verify_true;
1310       s->cleanup = socket_cleanup;
1311     }
1312   s->read_selected = TRUE;
1313   return s;
1314 }
1315
1316 select_record *
1317 fhandler_socket::select_write (select_record *s)
1318 {
1319   if (!s)
1320     {
1321       s = new select_record;
1322       s->startup = start_thread_socket;
1323       s->poll = poll_socket;
1324       s->verify = verify_true;
1325       s->cleanup = socket_cleanup;
1326     }
1327   s->write_selected = TRUE;
1328   return s;
1329 }
1330
1331 select_record *
1332 fhandler_socket::select_except (select_record *s)
1333 {
1334   if (!s)
1335     {
1336       s = new select_record;
1337       s->startup = start_thread_socket;
1338       s->poll = poll_socket;
1339       s->verify = verify_true;
1340       s->cleanup = socket_cleanup;
1341     }
1342   s->except_selected = TRUE;
1343   return s;
1344 }
1345
1346 static int
1347 peek_windows (select_record *me, int)
1348 {
1349   MSG m;
1350   HANDLE h;
1351   set_handle_or_return_if_not_open (h, me);
1352
1353   if (me->read_selected && me->read_ready)
1354     return 1;
1355
1356   if (PeekMessage (&m, (HWND) h, 0, 0, PM_NOREMOVE))
1357     {
1358       me->read_ready = TRUE;
1359       select_printf ("window %d(%p) ready", me->fd, me->fh->get_handle ());
1360       return 1;
1361     }
1362
1363   select_printf ("window %d(%p) not ready", me->fd, me->fh->get_handle ());
1364   return me->write_ready;
1365 }
1366
1367 static int
1368 poll_windows (select_record *me, fd_set *readfds, fd_set *writefds,
1369               fd_set *exceptfds)
1370 {
1371
1372   return peek_windows (me, 0) ?
1373          set_bits (me, readfds, writefds, exceptfds) :
1374          0;
1375 }
1376
1377 MAKEready (windows)
1378
1379 select_record *
1380 fhandler_windows::select_read (select_record *s)
1381 {
1382   if (!s)
1383     {
1384       s = new select_record;
1385       s->startup = no_startup;
1386       s->poll = poll_windows;
1387       s->verify = poll_windows;
1388     }
1389   s->h = get_handle ();
1390   s->read_selected = TRUE;
1391   s->h = get_handle ();
1392   s->windows_handle = TRUE;
1393   return s;
1394 }
1395
1396 select_record *
1397 fhandler_windows::select_write (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->write_selected = TRUE;
1408   s->write_ready = TRUE;
1409   s->windows_handle = TRUE;
1410   return s;
1411 }
1412
1413 select_record *
1414 fhandler_windows::select_except (select_record *s)
1415 {
1416   if (!s)
1417     {
1418       s = new select_record;
1419       s->startup = no_startup;
1420       s->poll = set_bits;
1421       s->verify = verify_ok;
1422     }
1423   s->h = get_handle ();
1424   s->except_selected = TRUE;
1425   s->except_ready = TRUE;
1426   s->windows_handle = TRUE;
1427   return s;
1428 }