OSDN Git Service

* select.cc (peek_console): Don't report read_ready on mouse events unless we
[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) <= bg_eof)
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) <= bg_eof)
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 == MOUSE_EVENT &&
639                  (irec.Event.MouseEvent.dwEventFlags == 0 ||
640                   irec.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK))
641           {
642             if (fh->mouse_aware ())
643               return me->read_ready = 1;
644           }
645         else if (irec.EventType == KEY_EVENT && irec.Event.KeyEvent.bKeyDown == TRUE &&
646                  (irec.Event.KeyEvent.uChar.AsciiChar || get_nonascii_key (irec, tmpbuf)))
647           return me->read_ready = 1;
648
649         /* Read and discard the event */
650         ReadConsoleInput (h, &irec, 1, &events_read);
651       }
652
653   return me->write_ready;
654 }
655
656 static int
657 poll_console (select_record *me, fd_set *readfds, fd_set *writefds,
658               fd_set *exceptfds)
659 {
660   return peek_console (me, 0) ?
661          set_bits (me, readfds, writefds, exceptfds) :
662          0;
663 }
664
665 MAKEready (console)
666
667 select_record *
668 fhandler_console::select_read (select_record *s)
669 {
670   if (!s)
671     {
672       s = new select_record;
673       s->startup = no_startup;
674       s->poll = poll_console;
675       s->verify = poll_console;
676       set_cursor_maybe ();
677     }
678
679   s->h = get_handle ();
680   s->read_selected = TRUE;
681   return s;
682 }
683
684 select_record *
685 fhandler_console::select_write (select_record *s)
686 {
687   if (!s)
688     {
689       s = new select_record;
690       s->startup = no_startup;
691       s->poll = poll_console;
692       s->verify = no_verify;
693       set_cursor_maybe ();
694     }
695
696   s->write_selected = TRUE;
697   s->write_ready = TRUE;
698   return s;
699 }
700
701 select_record *
702 fhandler_console::select_except (select_record *s)
703 {
704   if (!s)
705     {
706       s = new select_record;
707       s->startup = no_startup;
708       s->poll = poll_console;
709       s->verify = no_verify;
710       set_cursor_maybe ();
711     }
712
713   s->except_selected = TRUE;
714   return s;
715 }
716
717 int
718 fhandler_tty_common::ready_for_read (int fd, DWORD howlong, int ignra)
719 {
720 #if 0
721   if (myself->pgid && get_ttyp ()->getpgid () != myself->pgid &&
722         myself->ctty == ttynum) // background process?
723     return 1;   // Yes. Let read return an error
724 #endif
725   return ((fhandler_pipe*)this)->fhandler_pipe::ready_for_read (fd, howlong, ignra);
726 }
727
728 select_record *
729 fhandler_tty_common::select_read (select_record *s)
730 {
731   return ((fhandler_pipe*)this)->fhandler_pipe::select_read (s);
732 }
733
734 select_record *
735 fhandler_tty_common::select_write (select_record *s)
736 {
737   return ((fhandler_pipe *)this)->fhandler_pipe::select_write (s);
738 }
739
740 select_record *
741 fhandler_tty_common::select_except (select_record *s)
742 {
743   return ((fhandler_pipe *)this)->fhandler_pipe::select_except (s);
744 }
745
746 select_record *
747 fhandler_dev_null::select_read (select_record *s)
748 {
749   if (!s)
750     {
751       s = new select_record;
752       s->startup = no_startup;
753       s->poll = set_bits;
754       s->verify = no_verify;
755     }
756   s->h = get_handle ();
757   s->read_selected = TRUE;
758   return s;
759 }
760
761 select_record *
762 fhandler_dev_null::select_write (select_record *s)
763 {
764   if (!s)
765     {
766       s = new select_record;
767       s->startup = no_startup;
768       s->poll = set_bits;
769       s->verify = no_verify;
770     }
771   s->h = get_handle ();
772   s->write_selected = TRUE;
773   return s;
774 }
775
776 select_record *
777 fhandler_dev_null::select_except (select_record *s)
778 {
779   if (!s)
780     {
781       s = new select_record;
782       s->startup = no_startup;
783       s->poll = set_bits;
784       s->verify = no_verify;
785     }
786   s->h = get_handle ();
787   s->except_selected = TRUE;
788   s->except_ready = TRUE;
789   return s;
790 }
791
792 static int start_thread_serial (select_record *me, select_stuff *stuff);
793
794 struct serialinf
795   {
796     HANDLE thread;
797     BOOL stop_thread_serial;
798     select_record *start;
799   };
800
801 static int
802 peek_serial (select_record *s, int)
803 {
804   DWORD ev;
805   COMSTAT st;
806
807   fhandler_serial *fh = (fhandler_serial *)s->fh;
808
809   if (fh->get_readahead_valid () || fh->overlapped_armed < 0)
810     return s->read_ready = 1;
811
812   select_printf ("fh->overlapped_armed %d", fh->overlapped_armed);
813
814   HANDLE h;
815   set_handle_or_return_if_not_open (h, s);
816   int ready = 0;
817
818   if (s->read_selected && s->read_ready || (s->write_selected && s->write_ready))
819     {
820       select_printf ("already ready");
821       ready = 1;
822       goto out;
823     }
824
825   (void) SetCommMask (h, EV_RXCHAR);
826
827   if (!fh->overlapped_armed)
828     {
829       DWORD ev;
830       COMSTAT st;
831
832       ResetEvent (fh->io_status.hEvent);
833
834       if (!ClearCommError (h, &ev, &st))
835         {
836           debug_printf ("ClearCommError");
837           goto err;
838         }
839       else if (st.cbInQue)
840         return s->read_ready = 1;
841       else if (WaitCommEvent (h, &ev, &fh->io_status))
842         return s->read_ready = 1;
843       else if (GetLastError () == ERROR_IO_PENDING)
844         fh->overlapped_armed = 1;
845       else
846         {
847           debug_printf ("WaitCommEvent");
848           goto err;
849         }
850     }
851
852   HANDLE w4[2];
853   DWORD to;
854
855   w4[0] = fh->io_status.hEvent;
856   w4[1] = signal_arrived;
857   to = 10;
858
859   switch (WaitForMultipleObjects (2, w4, FALSE, to))
860     {
861     case WAIT_OBJECT_0:
862       if (!ClearCommError (h, &ev, &st))
863         {
864           debug_printf ("ClearCommError");
865           goto err;
866         }
867       else if (!st.cbInQue)
868         Sleep (to);
869       else
870         {
871           return s->read_ready = 1;
872           select_printf ("got something");
873         }
874       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
875       break;
876     case WAIT_OBJECT_0 + 1:
877       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
878       select_printf ("interrupt");
879       set_sig_errno (EINTR);
880       ready = -1;
881       break;
882     case WAIT_TIMEOUT:
883       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
884       break;
885     default:
886       PurgeComm (h, PURGE_TXABORT | PURGE_RXABORT);
887       debug_printf ("WaitForMultipleObjects");
888       goto err;
889     }
890
891 out:
892   return ready;
893
894 err:
895   if (GetLastError () == ERROR_OPERATION_ABORTED)
896     {
897       select_printf ("operation aborted");
898       return ready;
899     }
900
901   __seterrno ();
902   s->saw_error = TRUE;
903   select_printf ("error %E");
904   return -1;
905 }
906
907 static DWORD WINAPI
908 thread_serial (void *arg)
909 {
910   serialinf *si = (serialinf *)arg;
911   BOOL gotone= FALSE;
912
913   for (;;)
914     {
915       select_record *s = si->start;
916       while ((s = s->next))
917         if (s->startup == start_thread_serial)
918           {
919             if (peek_serial (s, 0))
920               gotone = TRUE;
921           }
922       if (si->stop_thread_serial)
923         {
924           select_printf ("stopping");
925           break;
926         }
927       if (gotone)
928         break;
929     }
930
931   select_printf ("exiting");
932   return 0;
933 }
934
935 static int
936 start_thread_serial (select_record *me, select_stuff *stuff)
937 {
938   if (stuff->device_specific[FHDEVN(FH_SERIAL)])
939     {
940       me->h = ((pipeinf *) stuff->device_specific[FHDEVN(FH_SERIAL)])->thread;
941       return 1;
942     }
943   serialinf *si = new serialinf;
944   si->start = &stuff->start;
945   si->stop_thread_serial = FALSE;
946   si->thread = me->h = makethread (thread_serial, (LPVOID)si, 0, "select_serial");
947   if (!me->h)
948     return 0;
949   stuff->device_specific[FHDEVN(FH_SERIAL)] = (void *)si;
950   return 1;
951 }
952
953 static void
954 serial_cleanup (select_record *, select_stuff *stuff)
955 {
956   serialinf *si = (serialinf *)stuff->device_specific[FHDEVN(FH_SERIAL)];
957   if (si && si->thread)
958     {
959       si->stop_thread_serial = TRUE;
960       WaitForSingleObject (si->thread, INFINITE);
961       CloseHandle (si->thread);
962       delete si;
963       stuff->device_specific[FHDEVN(FH_SERIAL)] = NULL;
964     }
965 }
966
967 static int
968 poll_serial (select_record *me, fd_set *readfds, fd_set *writefds,
969            fd_set *exceptfds)
970
971 {
972   return peek_serial (me, 0) ?
973          set_bits (me, readfds, writefds, exceptfds) :
974          0;
975 }
976
977 MAKEready (serial)
978
979 select_record *
980 fhandler_serial::select_read (select_record *s)
981 {
982   if (!s)
983     {
984       s = new select_record;
985       s->startup = start_thread_serial;
986       s->poll = poll_serial;
987       s->verify = verify_ok;
988       s->cleanup = serial_cleanup;
989     }
990   s->read_selected = TRUE;
991   return s;
992 }
993
994 select_record *
995 fhandler_serial::select_write (select_record *s)
996 {
997   if (!s)
998     {
999       s = new select_record;
1000       s->startup = no_startup;
1001       s->poll = set_bits;
1002       s->verify = verify_ok;
1003     }
1004   s->h = get_handle ();
1005   s->write_selected = TRUE;
1006   s->write_ready = TRUE;
1007   return s;
1008 }
1009
1010 select_record *
1011 fhandler_serial::select_except (select_record *s)
1012 {
1013   if (!s)
1014     {
1015       s = new select_record;
1016       s->startup = no_startup;
1017       s->poll = set_bits;
1018       s->verify = verify_ok;
1019     }
1020   s->h = NULL;
1021   s->except_selected = FALSE;   // Can't do this
1022   return s;
1023 }
1024
1025 int
1026 fhandler_base::ready_for_read (int, DWORD, int)
1027 {
1028   return 1;
1029 }
1030
1031 select_record *
1032 fhandler_base::select_read (select_record *s)
1033 {
1034   if (!s)
1035     {
1036       s = new select_record;
1037       s->startup = no_startup;
1038       s->poll = set_bits;
1039       s->verify = verify_ok;
1040     }
1041   s->h = get_handle ();
1042   s->read_selected = TRUE;
1043   s->read_ready = TRUE;
1044   return s;
1045 }
1046
1047 select_record *
1048 fhandler_base::select_write (select_record *s)
1049 {
1050   if (!s)
1051     {
1052       s = new select_record;
1053       s->startup = no_startup;
1054       s->poll = set_bits;
1055       s->verify = verify_ok;
1056     }
1057   s->h = get_handle ();
1058   s->write_selected = TRUE;
1059   s->write_ready = TRUE;
1060   return s;
1061 }
1062
1063 select_record *
1064 fhandler_base::select_except (select_record *s)
1065 {
1066   if (!s)
1067     {
1068       s = new select_record;
1069       s->startup = no_startup;
1070       s->poll = set_bits;
1071       s->verify = verify_ok;
1072     }
1073   s->h = NULL;
1074   s->write_selected = TRUE;
1075   return s;
1076 }
1077
1078 struct socketinf
1079   {
1080     HANDLE thread;
1081     winsock_fd_set readfds, writefds, exceptfds;
1082     SOCKET exitsock;
1083     struct sockaddr_in sin;
1084     select_record *start;
1085   };
1086
1087 static int
1088 peek_socket (select_record *me, int)
1089 {
1090   winsock_fd_set ws_readfds, ws_writefds, ws_exceptfds;
1091   struct timeval tv = {0, 0};
1092   WINSOCK_FD_ZERO (&ws_readfds);
1093   WINSOCK_FD_ZERO (&ws_writefds);
1094   WINSOCK_FD_ZERO (&ws_exceptfds);
1095   int gotone = 0;
1096
1097   HANDLE h;
1098   set_handle_or_return_if_not_open (h, me);
1099   select_printf ("considering handle %p", h);
1100
1101   if (me->read_selected)
1102     {
1103       select_printf ("adding read fd_set %s, fd %d", me->fh->get_name (),
1104                      me->fd);
1105       WINSOCK_FD_SET (h, &ws_readfds);
1106     }
1107   if (me->write_selected)
1108     {
1109       select_printf ("adding write fd_set %s, fd %d", me->fh->get_name (),
1110                      me->fd);
1111       WINSOCK_FD_SET (h, &ws_writefds);
1112     }
1113   if (me->except_selected)
1114     {
1115       select_printf ("adding except fd_set %s, fd %d", me->fh->get_name (),
1116                      me->fd);
1117       WINSOCK_FD_SET (h, &ws_exceptfds);
1118     }
1119   int r = WINSOCK_SELECT (0, &ws_readfds, &ws_writefds, &ws_exceptfds, &tv);
1120   select_printf ("WINSOCK_SELECT returned %d", r);
1121   if (r == -1)
1122     {
1123       select_printf ("error %d", WSAGetLastError ());
1124       return 0;
1125     }
1126
1127   if (WINSOCK_FD_ISSET (h, &ws_readfds) || (me->read_selected && me->read_ready))
1128     gotone = me->read_ready = TRUE;
1129   if (WINSOCK_FD_ISSET (h, &ws_writefds) || (me->write_selected && me->write_ready))
1130     gotone = me->write_ready = TRUE;
1131   if (WINSOCK_FD_ISSET (h, &ws_exceptfds) || (me->except_selected && me->except_ready))
1132     gotone = me->except_ready = TRUE;
1133   return gotone;
1134 }
1135
1136 static int
1137 poll_socket (select_record *me, fd_set *readfds, fd_set *writefds,
1138            fd_set *exceptfds)
1139 {
1140   return peek_socket (me, 0) ?
1141          set_bits (me, readfds, writefds, exceptfds) :
1142          0;
1143 }
1144
1145 MAKEready (socket)
1146
1147 static int start_thread_socket (select_record *, select_stuff *);
1148
1149 static DWORD WINAPI
1150 thread_socket (void *arg)
1151 {
1152   socketinf *si = (socketinf *)arg;
1153
1154   select_printf ("stuff_start %p", &si->start);
1155   int r = WINSOCK_SELECT (0, &si->readfds, &si->writefds, &si->exceptfds, NULL);
1156   select_printf ("Win32 select returned %d", r);
1157   if (r == -1)
1158     select_printf ("error %d", WSAGetLastError ());
1159   select_record *s = si->start;
1160   while ((s = s->next))
1161     if (s->startup == start_thread_socket)
1162         {
1163           HANDLE h = s->fh->get_handle ();
1164           select_printf ("s %p, testing fd %d (%s)", s, s->fd, s->fh->get_name ());
1165           if (WINSOCK_FD_ISSET (h, &si->readfds))
1166             {
1167               select_printf ("read_ready");
1168               s->read_ready = TRUE;
1169             }
1170           if (WINSOCK_FD_ISSET (h, &si->writefds))
1171             {
1172               select_printf ("write_ready");
1173               s->write_ready = TRUE;
1174             }
1175           if (WINSOCK_FD_ISSET (h, &si->exceptfds))
1176             {
1177               select_printf ("except_ready");
1178               s->except_ready = TRUE;
1179             }
1180         }
1181
1182   if (WINSOCK_FD_ISSET (si->exitsock, &si->readfds))
1183     select_printf ("saw exitsock read");
1184
1185   return 0;
1186 }
1187
1188 extern "C" unsigned long htonl (unsigned long);
1189
1190 static int
1191 start_thread_socket (select_record *me, select_stuff *stuff)
1192 {
1193   socketinf *si;
1194
1195   if ((si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)]))
1196     {
1197       me->h = si->thread;
1198       return 1;
1199     }
1200
1201   si = new socketinf;
1202   WINSOCK_FD_ZERO (&si->readfds);
1203   WINSOCK_FD_ZERO (&si->writefds);
1204   WINSOCK_FD_ZERO (&si->exceptfds);
1205   select_record *s = &stuff->start;
1206   while ((s = s->next))
1207     if (s->startup == start_thread_socket)
1208       {
1209         HANDLE h = s->fh->get_handle ();
1210         select_printf ("Handle %p", h);
1211         if (s->read_selected)
1212           {
1213             WINSOCK_FD_SET (h, &si->readfds);
1214             select_printf ("Added to readfds");
1215           }
1216         if (s->write_selected)
1217           {
1218             WINSOCK_FD_SET (h, &si->writefds);
1219             select_printf ("Added to writefds");
1220           }
1221         if (s->except_selected)
1222           {
1223             WINSOCK_FD_SET (h, &si->exceptfds);
1224             select_printf ("Added to exceptfds");
1225           }
1226       }
1227
1228   if ((si->exitsock = socket (PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
1229     {
1230       set_winsock_errno ();
1231       select_printf ("cannot create socket, %E");
1232       return -1;
1233     }
1234   /* Allow rapid reuse of the port. */
1235   int tmp = 1;
1236   (void) setsockopt (si->exitsock, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp, sizeof (tmp));
1237
1238   int sin_len = sizeof(si->sin);
1239   memset (&si->sin, 0, sizeof (si->sin));
1240   si->sin.sin_family = AF_INET;
1241   si->sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1242   if (bind (si->exitsock, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1243     {
1244       select_printf ("cannot bind socket, %E");
1245       goto err;
1246     }
1247
1248   if (getsockname (si->exitsock, (struct sockaddr *) &si->sin, &sin_len) < 0)
1249     {
1250       select_printf ("getsockname error");
1251       goto err;
1252     }
1253
1254   if (listen (si->exitsock, 1))
1255     {
1256       select_printf ("listen failed, %E");
1257       goto err;
1258     }
1259
1260   select_printf ("exitsock %p", si->exitsock);
1261   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->readfds);
1262   WINSOCK_FD_SET ((HANDLE) si->exitsock, &si->exceptfds);
1263   stuff->device_specific[FHDEVN(FH_SOCKET)] = (void *) si;
1264   si->start = &stuff->start;
1265   select_printf ("stuff_start %p", &stuff->start);
1266   si->thread = me->h = makethread (thread_socket, (LPVOID)si, 0,
1267                                   "select_socket");
1268   return !!me->h;
1269
1270 err:
1271   set_winsock_errno ();
1272   closesocket (si->exitsock);
1273   return -1;
1274 }
1275
1276 void
1277 socket_cleanup (select_record *, select_stuff *stuff)
1278 {
1279   socketinf *si = (socketinf *)stuff->device_specific[FHDEVN(FH_SOCKET)];
1280   select_printf ("si %p si->thread %p", si, si ? si->thread : NULL);
1281   if (si && si->thread)
1282     {
1283       select_printf ("connection to si->exitsock %p", si->exitsock);
1284       SOCKET s = socket (AF_INET, SOCK_STREAM, 0);
1285       /* Connecting to si->exitsock will cause any executing select to wake
1286          up.  When this happens then the exitsock condition will cause the
1287          thread to terminate. */
1288       if (connect (s, (struct sockaddr *) &si->sin, sizeof (si->sin)) < 0)
1289         {
1290           set_winsock_errno ();
1291           select_printf ("connect failed");
1292           /* FIXME: now what? */
1293         }
1294       shutdown (s, 2);
1295       closesocket (s);
1296
1297       /* Wait for thread to go away */
1298       WaitForSingleObject (si->thread, INFINITE);
1299       shutdown (si->exitsock, 2);
1300       closesocket (si->exitsock);
1301       CloseHandle (si->thread);
1302       stuff->device_specific[FHDEVN(FH_SOCKET)] = NULL;
1303       delete si;
1304     }
1305   select_printf ("returning");
1306 }
1307
1308 select_record *
1309 fhandler_socket::select_read (select_record *s)
1310 {
1311   if (!s)
1312     {
1313       s = new select_record;
1314       s->startup = start_thread_socket;
1315       s->poll = poll_socket;
1316       s->verify = verify_true;
1317       s->cleanup = socket_cleanup;
1318     }
1319   s->read_selected = TRUE;
1320   return s;
1321 }
1322
1323 select_record *
1324 fhandler_socket::select_write (select_record *s)
1325 {
1326   if (!s)
1327     {
1328       s = new select_record;
1329       s->startup = start_thread_socket;
1330       s->poll = poll_socket;
1331       s->verify = verify_true;
1332       s->cleanup = socket_cleanup;
1333     }
1334   s->write_selected = TRUE;
1335   return s;
1336 }
1337
1338 select_record *
1339 fhandler_socket::select_except (select_record *s)
1340 {
1341   if (!s)
1342     {
1343       s = new select_record;
1344       s->startup = start_thread_socket;
1345       s->poll = poll_socket;
1346       s->verify = verify_true;
1347       s->cleanup = socket_cleanup;
1348     }
1349   s->except_selected = TRUE;
1350   return s;
1351 }
1352
1353 static int
1354 peek_windows (select_record *me, int)
1355 {
1356   MSG m;
1357   HANDLE h;
1358   set_handle_or_return_if_not_open (h, me);
1359
1360   if (me->read_selected && me->read_ready)
1361     return 1;
1362
1363   if (PeekMessage (&m, (HWND) h, 0, 0, PM_NOREMOVE))
1364     {
1365       me->read_ready = TRUE;
1366       select_printf ("window %d(%p) ready", me->fd, me->fh->get_handle ());
1367       return 1;
1368     }
1369
1370   select_printf ("window %d(%p) not ready", me->fd, me->fh->get_handle ());
1371   return me->write_ready;
1372 }
1373
1374 static int
1375 poll_windows (select_record *me, fd_set *readfds, fd_set *writefds,
1376               fd_set *exceptfds)
1377 {
1378
1379   return peek_windows (me, 0) ?
1380          set_bits (me, readfds, writefds, exceptfds) :
1381          0;
1382 }
1383
1384 MAKEready (windows)
1385
1386 select_record *
1387 fhandler_windows::select_read (select_record *s)
1388 {
1389   if (!s)
1390     {
1391       s = new select_record;
1392       s->startup = no_startup;
1393       s->poll = poll_windows;
1394       s->verify = poll_windows;
1395     }
1396   s->h = get_handle ();
1397   s->read_selected = TRUE;
1398   s->h = get_handle ();
1399   s->windows_handle = TRUE;
1400   return s;
1401 }
1402
1403 select_record *
1404 fhandler_windows::select_write (select_record *s)
1405 {
1406   if (!s)
1407     {
1408       s = new select_record;
1409       s->startup = no_startup;
1410       s->poll = set_bits;
1411       s->verify = verify_ok;
1412     }
1413   s->h = get_handle ();
1414   s->write_selected = TRUE;
1415   s->write_ready = TRUE;
1416   s->windows_handle = TRUE;
1417   return s;
1418 }
1419
1420 select_record *
1421 fhandler_windows::select_except (select_record *s)
1422 {
1423   if (!s)
1424     {
1425       s = new select_record;
1426       s->startup = no_startup;
1427       s->poll = set_bits;
1428       s->verify = verify_ok;
1429     }
1430   s->h = get_handle ();
1431   s->except_selected = TRUE;
1432   s->except_ready = TRUE;
1433   s->windows_handle = TRUE;
1434   return s;
1435 }