OSDN Git Service

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