-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathselect.cc
2415 lines (2195 loc) · 59.6 KB
/
select.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* select.cc
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
/* The following line means that the BSD socket definitions for
fd_set, FD_ISSET etc. are used in this file. */
#define __INSIDE_CYGWIN_NET__
#include "winsup.h"
#include <stdlib.h>
#include <sys/param.h>
#include "ntdll.h"
#define USE_SYS_TYPES_FD_SET
#include <winsock2.h>
#include <netdb.h>
#include "cygerrno.h"
#include "security.h"
#include "path.h"
#include "fhandler.h"
#include "select.h"
#include "dtable.h"
#include "cygheap.h"
#include "pinfo.h"
#include "sigproc.h"
#include "cygtls.h"
/*
* All these defines below should be in sys/types.h
* but because of the includes above, they may not have
* been included. We create special UNIX_xxxx versions here.
*/
#ifndef NBBY
#define NBBY 8 /* number of bits in a byte */
#endif /* NBBY */
/*
* Select uses bit masks of file descriptors in longs.
* These macros manipulate such bit fields (the filesystem macros use chars).
* FD_SETSIZE may be defined by the user, but the default here
* should be >= NOFILE (param.h).
*/
#define UNIX_NFDBITS (sizeof (fd_mask) * NBBY) /* bits per mask */
#ifndef unix_howmany
#define unix_howmany(x,y) (((x)+((y)-1))/(y))
#endif
#define unix_fd_set fd_set
#define NULL_fd_set ((fd_set *) NULL)
#define sizeof_fd_set(n) \
((size_t) (NULL_fd_set->fds_bits + unix_howmany ((n), UNIX_NFDBITS)))
#define UNIX_FD_SET(n, p) \
((p)->fds_bits[(n)/UNIX_NFDBITS] |= (1L << ((n) % UNIX_NFDBITS)))
#define UNIX_FD_CLR(n, p) \
((p)->fds_bits[(n)/UNIX_NFDBITS] &= ~(1L << ((n) % UNIX_NFDBITS)))
#define UNIX_FD_ISSET(n, p) \
((p)->fds_bits[(n)/UNIX_NFDBITS] & (1L << ((n) % UNIX_NFDBITS)))
#define UNIX_FD_ZERO(p, n) \
memset ((caddr_t) (p), 0, sizeof_fd_set ((n)))
#define allocfd_set(n) ({\
size_t __sfds = sizeof_fd_set (n) + 8; \
void *__res = alloca (__sfds); \
memset (__res, 0, __sfds); \
(fd_set *) __res; \
})
#define set_handle_or_return_if_not_open(h, s) \
h = (s)->fh->get_handle (); \
if (cygheap->fdtab.not_open ((s)->fd)) \
{ \
(s)->thread_errno = EBADF; \
return -1; \
}
static int select (int, fd_set *, fd_set *, fd_set *, LONGLONG);
/* The main select code. */
extern "C" int
pselect (int maxfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
const struct timespec *to, const sigset_t *set)
{
sigset_t oldset = _my_tls.sigmask;
__try
{
if (set)
set_signal_mask (_my_tls.sigmask, *set);
select_printf ("pselect (%d, %p, %p, %p, %p, %p)", maxfds, readfds, writefds, exceptfds, to, set);
pthread_testcancel ();
int res;
if (maxfds < 0)
{
set_errno (EINVAL);
res = -1;
}
else
{
/* Convert to microseconds or -1 if to == NULL */
LONGLONG us = to ? to->tv_sec * USPERSEC
+ (to->tv_nsec + (NSPERSEC/USPERSEC) - 1)
/ (NSPERSEC/USPERSEC)
: -1LL;
if (to)
select_printf ("to->tv_sec %ld, to->tv_nsec %ld, us %D", to->tv_sec, to->tv_nsec, us);
else
select_printf ("to NULL, us %D", us);
res = select (maxfds, readfds ?: allocfd_set (maxfds),
writefds ?: allocfd_set (maxfds),
exceptfds ?: allocfd_set (maxfds), us);
}
syscall_printf ("%R = select (%d, %p, %p, %p, %p)", res, maxfds, readfds,
writefds, exceptfds, to);
if (set)
set_signal_mask (_my_tls.sigmask, oldset);
return res;
}
__except (EFAULT) {}
__endtry
return -1;
}
/* select () is just a wrapper on pselect (). */
extern "C" int
cygwin_select (int maxfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
struct timeval *to)
{
struct timespec ts;
if (to)
{
ts.tv_sec = to->tv_sec;
ts.tv_nsec = to->tv_usec * 1000;
}
return pselect (maxfds, readfds, writefds, exceptfds,
to ? &ts : NULL, NULL);
}
/* This function is arbitrarily split out from cygwin_select to avoid odd
gcc issues with the use of allocfd_set and improper constructor handling
for the sel variable. */
static int
select (int maxfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
LONGLONG us)
{
select_stuff::wait_states wait_state = select_stuff::select_set_zero;
int ret = 0;
/* Record the current time for later use. */
LONGLONG start_time = get_clock (CLOCK_REALTIME)->usecs ();
select_stuff sel;
sel.return_on_signal = 0;
/* Allocate fd_set structures to store incoming fd sets. */
fd_set *readfds_in = allocfd_set (maxfds);
fd_set *writefds_in = allocfd_set (maxfds);
fd_set *exceptfds_in = allocfd_set (maxfds);
memcpy (readfds_in, readfds, sizeof_fd_set (maxfds));
memcpy (writefds_in, writefds, sizeof_fd_set (maxfds));
memcpy (exceptfds_in, exceptfds, sizeof_fd_set (maxfds));
do
{
/* Build the select record per fd linked list and set state as
needed. */
for (int i = 0; i < maxfds; i++)
if (!sel.test_and_set (i, readfds_in, writefds_in, exceptfds_in))
{
select_printf ("aborting due to test_and_set error");
return -1; /* Invalid fd, maybe? */
}
select_printf ("sel.always_ready %d", sel.always_ready);
if (sel.always_ready || us == 0)
/* Catch any active fds via sel.poll () below */
wait_state = select_stuff::select_ok;
else
/* wait for an fd to become active or time out */
wait_state = sel.wait (readfds, writefds, exceptfds, us);
select_printf ("sel.wait returns %d", wait_state);
if (wait_state == select_stuff::select_ok)
{
UNIX_FD_ZERO (readfds, maxfds);
UNIX_FD_ZERO (writefds, maxfds);
UNIX_FD_ZERO (exceptfds, maxfds);
/* Set bit mask from sel records. This also sets ret to the
right value >= 0, matching the number of bits set in the
fds records. if ret is 0, continue to loop. */
ret = sel.poll (readfds, writefds, exceptfds);
if (ret < 0)
wait_state = select_stuff::select_signalled;
else if (!ret)
wait_state = select_stuff::select_set_zero;
}
/* Always clean up everything here. If we're looping then build it
all up again. */
sel.cleanup ();
sel.destroy ();
/* Check and recalculate timeout. */
if (us != -1LL && wait_state == select_stuff::select_set_zero)
{
select_printf ("recalculating us");
LONGLONG now = get_clock (CLOCK_REALTIME)->usecs ();
if (now >= (start_time + us))
{
select_printf ("timed out after verification");
/* Set descriptor bits to zero per POSIX. */
UNIX_FD_ZERO (readfds, maxfds);
UNIX_FD_ZERO (writefds, maxfds);
UNIX_FD_ZERO (exceptfds, maxfds);
wait_state = select_stuff::select_ok;
ret = 0;
}
else
{
us -= (now - start_time);
start_time = now;
select_printf ("us now %D", us);
}
}
}
while (wait_state == select_stuff::select_set_zero);
if (wait_state < select_stuff::select_ok)
ret = -1;
return ret;
}
/* Call cleanup functions for all inspected fds. Gets rid of any
executing threads. */
void
select_stuff::cleanup ()
{
select_record *s = &start;
select_printf ("calling cleanup routines");
while ((s = s->next))
if (s->cleanup)
{
s->cleanup (s, this);
s->cleanup = NULL;
}
}
/* Destroy all storage associated with select stuff. */
inline void
select_stuff::destroy ()
{
select_record *s;
select_record *snext = start.next;
select_printf ("deleting select records");
while ((s = snext))
{
snext = s->next;
delete s;
}
start.next = NULL;
}
select_stuff::~select_stuff ()
{
cleanup ();
destroy ();
}
#ifdef DEBUGGING
void
select_record::dump_select_record ()
{
select_printf ("fd %d, h %p, fh %p, thread_errno %d, windows_handle %p",
fd, h, fh, thread_errno, windows_handle);
select_printf ("read_ready %d, write_ready %d, except_ready %d",
read_ready, write_ready, except_ready);
select_printf ("read_selected %d, write_selected %d, except_selected %d, except_on_write %d",
read_selected, write_selected, except_selected, except_on_write);
select_printf ("startup %p, peek %p, verify %p cleanup %p, next %p",
startup, peek, verify, cleanup, next);
}
#endif /*DEBUGGING*/
/* Add a record to the select chain */
bool
select_stuff::test_and_set (int i, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds)
{
if (!UNIX_FD_ISSET (i, readfds) && !UNIX_FD_ISSET (i, writefds)
&& ! UNIX_FD_ISSET (i, exceptfds))
return true;
select_record *s = new select_record;
if (!s)
return false;
s->next = start.next;
start.next = s;
if (UNIX_FD_ISSET (i, readfds) && !cygheap->fdtab.select_read (i, this))
goto err;
if (UNIX_FD_ISSET (i, writefds) && !cygheap->fdtab.select_write (i, this))
goto err;
if (UNIX_FD_ISSET (i, exceptfds) && !cygheap->fdtab.select_except (i, this))
goto err; /* error */
if (s->read_ready || s->write_ready || s->except_ready)
always_ready = true;
if (s->windows_handle)
windows_used = true;
#ifdef DEBUGGING
s->dump_select_record ();
#endif
return true;
err:
start.next = s->next;
delete s;
return false;
}
/* The heart of select. Waits for an fd to do something interesting. */
select_stuff::wait_states
select_stuff::wait (fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
LONGLONG us)
{
HANDLE w4[MAXIMUM_WAIT_OBJECTS];
select_record *s = &start;
DWORD m = 0, timer_idx = 0, cancel_idx = 0;
/* Always wait for signals. */
wait_signal_arrived here (w4[m++]);
/* Set a timeout, or not, for WMFO. */
DWORD wmfo_timeout = us ? INFINITE : 0;
/* Optionally wait for pthread cancellation. */
if ((w4[m] = pthread::get_cancel_event ()) != NULL)
cancel_idx = m++;
/* Loop through the select chain, starting up anything appropriate and
counting the number of active fds. */
DWORD startfds = m;
while ((s = s->next))
{
/* Make sure to leave space for the timer, if we have a finite timeout. */
if (m >= MAXIMUM_WAIT_OBJECTS - (us > 0LL ? 1 : 0))
{
set_sig_errno (EINVAL);
return select_error;
}
if (!s->startup (s, this))
{
s->set_select_errno ();
return select_error;
}
if (s->h != NULL)
{
for (DWORD i = startfds; i < m; i++)
if (w4[i] == s->h)
goto next_while;
w4[m++] = s->h;
}
next_while:;
}
/* Optionally create and set a waitable timer if a finite timeout has
been requested. Recycle cw_timer in the cygtls area so we only have
to create the timer once per thread. Since WFMO checks the handles
in order, we append the timer as last object, otherwise it's preferred
over actual events on the descriptors. */
HANDLE &wait_timer = _my_tls.locals.cw_timer;
if (us > 0LL)
{
NTSTATUS status;
if (!wait_timer)
{
status = NtCreateTimer (&wait_timer, TIMER_ALL_ACCESS, NULL,
NotificationTimer);
if (!NT_SUCCESS (status))
{
select_printf ("%y = NtCreateTimer ()\n", status);
return select_error;
}
}
LARGE_INTEGER ms_clock_ticks = { .QuadPart = -us * 10 };
status = NtSetTimer (wait_timer, &ms_clock_ticks, NULL, NULL, FALSE,
0, NULL);
if (!NT_SUCCESS (status))
{
select_printf ("%y = NtSetTimer (%D)\n",
status, ms_clock_ticks.QuadPart);
return select_error;
}
w4[m] = wait_timer;
timer_idx = m++;
}
debug_printf ("m %d, us %U, wmfo_timeout %d", m, us, wmfo_timeout);
DWORD wait_ret;
if (!windows_used)
wait_ret = WaitForMultipleObjects (m, w4, FALSE, wmfo_timeout);
else
/* Using MWMO_INPUTAVAILABLE is the officially supported solution for
the problem that the call to PeekMessage disarms the queue state
so that a subsequent MWFMO hangs, even if there are still messages
in the queue. */
wait_ret = MsgWaitForMultipleObjectsEx (m, w4, wmfo_timeout,
QS_ALLINPUT | QS_ALLPOSTMESSAGE,
MWMO_INPUTAVAILABLE);
select_printf ("wait_ret %d, m = %d. verifying", wait_ret, m);
if (timer_idx)
{
BOOLEAN current_state;
NtCancelTimer (wait_timer, ¤t_state);
}
wait_states res;
switch (wait_ret)
{
case WAIT_OBJECT_0:
select_printf ("signal received");
/* Need to get rid of everything when a signal occurs since we can't
be assured that a signal handler won't jump out of select entirely. */
cleanup ();
destroy ();
/* select() is always interrupted by a signal so set EINTR,
unconditionally, ignoring any SA_RESTART detection by
call_signal_handler(). */
_my_tls.call_signal_handler ();
set_sig_errno (EINTR);
res = select_signalled; /* Cause loop exit in cygwin_select */
break;
case WAIT_FAILED:
system_printf ("WaitForMultipleObjects failed, %E");
s = &start;
s->set_select_errno ();
res = select_error;
break;
case WAIT_TIMEOUT:
was_timeout:
select_printf ("timed out");
res = select_set_zero;
break;
case WAIT_OBJECT_0 + 1:
/* Cancel event? */
if (wait_ret == cancel_idx)
{
cleanup ();
destroy ();
pthread::static_cancel_self ();
/*NOTREACHED*/
}
fallthrough;
default:
/* Timer event? */
if (wait_ret == timer_idx)
goto was_timeout;
s = &start;
res = select_set_zero;
/* Some types of objects (e.g., consoles) wake up on "inappropriate"
events like mouse movements. The verify function will detect these
situations. If it returns false, then this wakeup was a false alarm
and we should go back to waiting. */
int ret = 0;
while ((s = s->next))
if (s->saw_error ())
{
set_errno (s->saw_error ());
res = select_error; /* Somebody detected an error */
goto out;
}
else if ((((wait_ret >= m && s->windows_handle)
|| s->h == w4[wait_ret]))
&& (ret = s->verify (s, readfds, writefds, exceptfds)) > 0)
res = select_ok;
else if (ret < 0)
{
res = select_signalled;
goto out;
}
select_printf ("res after verify %d", res);
break;
}
out:
select_printf ("returning %d", res);
return res;
}
static int
set_bits (select_record *me, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds)
{
int ready = 0;
fhandler_socket_wsock *sock;
select_printf ("me %p, testing fd %d (%s)", me, me->fd, me->fh->get_name ());
if (me->read_selected && me->read_ready)
{
UNIX_FD_SET (me->fd, readfds);
ready++;
}
if (me->write_selected && me->write_ready)
{
UNIX_FD_SET (me->fd, writefds);
if (me->except_on_write && (sock = me->fh->is_wsock_socket ()))
{
/* Set readfds entry in case of a failed connect. */
if (!me->read_ready && me->read_selected
&& sock->connect_state () == connect_failed)
{
UNIX_FD_SET (me->fd, readfds);
ready++;
}
}
ready++;
}
if (me->except_selected && me->except_ready)
{
UNIX_FD_SET (me->fd, exceptfds);
ready++;
}
select_printf ("ready %d", ready);
return ready;
}
/* Poll every fd in the select chain. Set appropriate fd in mask. */
int
select_stuff::poll (fd_set *readfds, fd_set *writefds, fd_set *exceptfds)
{
int n = 0;
select_record *s = &start;
while ((s = s->next))
{
int ret = s->peek ? s->peek (s, true) : 1;
if (ret < 0)
return -1;
n += (ret > 0) ? set_bits (s, readfds, writefds, exceptfds) : 0;
}
return n;
}
static int
verify_true (select_record *, fd_set *, fd_set *, fd_set *)
{
return 1;
}
static int
verify_ok (select_record *me, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds)
{
return set_bits (me, readfds, writefds, exceptfds);
}
static int
no_startup (select_record *, select_stuff *)
{
return 1;
}
static int
no_verify (select_record *, fd_set *, fd_set *, fd_set *)
{
return 0;
}
ssize_t
pipe_data_available (int fd, fhandler_base *fh, HANDLE h, int flags)
{
if (fh->get_device () == FH_PIPER)
{
DWORD nbytes_in_pipe;
if (!(flags & PDA_WRITE)
&& PeekNamedPipe (h, NULL, 0, NULL, &nbytes_in_pipe, NULL))
return nbytes_in_pipe;
return -1;
}
IO_STATUS_BLOCK iosb = {{0}, 0};
FILE_PIPE_LOCAL_INFORMATION fpli = {0};
NTSTATUS status;
status = NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
FilePipeLocalInformation);
if (!NT_SUCCESS (status))
{
/* If NtQueryInformationFile fails, optimistically assume the
pipe is writable. This could happen if we somehow
inherit a pipe that doesn't permit FILE_READ_ATTRIBUTES
access on the write end. */
select_printf ("fd %d, %s, NtQueryInformationFile failed, status %y",
fd, fh->get_name (), status);
switch (flags)
{
case PDA_WRITE:
return 1;
case PDA_SELECT | PDA_WRITE:
return PIPE_BUF;
default:
return -1;
}
}
if (flags & PDA_WRITE)
{
/* If there is anything available in the pipe buffer then signal
that. This means that a pipe could still block since you could
be trying to write more to the pipe than is available in the
buffer but that is the hazard of select().
Note that WriteQuotaAvailable is unreliable.
Usually WriteQuotaAvailable on the write side reflects the space
available in the inbound buffer on the read side. However, if a
pipe read is currently pending, WriteQuotaAvailable on the write side
is decremented by the number of bytes the read side is requesting.
So it's possible (even likely) that WriteQuotaAvailable is 0, even
if the inbound buffer on the read side is not full. This can lead to
a deadlock situation: The reader is waiting for data, but select
on the writer side assumes that no space is available in the read
side inbound buffer.
Consequentially, the only reliable information is available on the
read side, so fetch info from the read side via the pipe-specific
query handle. Use fpli.WriteQuotaAvailable as storage for the actual
interesting value, which is the InboundQuote on the write side,
decremented by the number of bytes of data in that buffer. */
/* Note: Do not use NtQueryInformationFile() for query_hdl because
NtQueryInformationFile() seems to interfere with reading pipes
in non-cygwin apps. Instead, use PeekNamedPipe() here. */
/* Note 2: we return the number of available bytes. Select for writing
returns writable *only* if at least PIPE_BUF bytes are left in the
buffer. If we can't fetch the real number of available bytes, the
number of bytes returned depends on the caller. For select we return
PIPE_BUF to fake writability, for writing we return 1 to allow
handling this fact. */
if (fh->get_device () == FH_PIPEW && fpli.WriteQuotaAvailable == 0)
{
HANDLE query_hdl = ((fhandler_pipe *) fh)->get_query_handle ();
if (!query_hdl)
query_hdl = ((fhandler_pipe *) fh)->temporary_query_hdl ();
if (!query_hdl) /* We cannot know actual write pipe space. */
return (flags & PDA_SELECT) ? PIPE_BUF : 1;
DWORD nbytes_in_pipe;
BOOL res =
PeekNamedPipe (query_hdl, NULL, 0, NULL, &nbytes_in_pipe, NULL);
if (!((fhandler_pipe *) fh)->get_query_handle ())
CloseHandle (query_hdl); /* Close temporary query_hdl */
if (!res) /* We cannot know actual write pipe space. */
return (flags & PDA_SELECT) ? PIPE_BUF : 1;
fpli.WriteQuotaAvailable = fpli.InboundQuota - nbytes_in_pipe;
}
if (fpli.WriteQuotaAvailable > 0)
{
paranoid_printf ("fd %d, %s, write: size %u, avail %u", fd,
fh->get_name (), fpli.InboundQuota,
fpli.WriteQuotaAvailable);
return fpli.WriteQuotaAvailable;
}
/* TODO: Buffer really full or non-Cygwin reader? */
}
else if (fpli.ReadDataAvailable)
{
paranoid_printf ("fd %d, %s, read avail %u", fd, fh->get_name (),
fpli.ReadDataAvailable);
return fpli.ReadDataAvailable;
}
if (fpli.NamedPipeState & FILE_PIPE_CLOSING_STATE)
return -1;
return 0;
}
static int
peek_pipe (select_record *s, bool from_select)
{
HANDLE h;
set_handle_or_return_if_not_open (h, s);
int gotone = 0;
fhandler_base *fh = (fhandler_base *) s->fh;
DWORD dev = fh->get_device ();
if (s->read_selected && dev != FH_PIPEW)
{
if (s->read_ready)
{
select_printf ("%s, already ready for read", fh->get_name ());
gotone = 1;
goto out;
}
switch (fh->get_major ())
{
case DEV_PTYM_MAJOR:
{
fhandler_pty_master *fhm = (fhandler_pty_master *) fh;
fhm->flush_to_slave ();
}
break;
default:
if (fh->get_readahead_valid ())
{
select_printf ("readahead");
gotone = s->read_ready = true;
goto out;
}
}
if (fh->bg_check (SIGTTIN, true) <= bg_eof)
{
gotone = s->read_ready = true;
goto out;
}
ssize_t n = pipe_data_available (s->fd, fh, h, PDA_SELECT);
/* On PTY masters, check if input from the echo pipe is available. */
if (n == 0 && fh->get_echo_handle ())
n = pipe_data_available (s->fd, fh, fh->get_echo_handle (), PDA_SELECT);
if (n < 0)
{
select_printf ("read: %s, n %d", fh->get_name (), n);
if (s->except_selected)
gotone += s->except_ready = true;
if (s->read_selected)
gotone += s->read_ready = true;
}
else if (n > 0)
{
select_printf ("read: %s, ready for read: avail %d", fh->get_name (), n);
gotone += s->read_ready = true;
}
if (!gotone && s->fh->hit_eof ())
{
select_printf ("read: %s, saw EOF", fh->get_name ());
if (s->except_selected)
gotone += s->except_ready = true;
if (s->read_selected)
gotone += s->read_ready = true;
}
}
out:
if (fh->get_major () == DEV_PTYM_MAJOR)
{
fhandler_pty_master *fhm = (fhandler_pty_master *) fh;
fhm->set_mask_flusho (s->read_ready);
}
h = fh->get_output_handle ();
if (s->write_selected && dev != FH_PIPER)
{
if (dev == FH_PIPEW && ((fhandler_pipe *) fh)->reader_closed ())
{
gotone += s->write_ready = true;
if (s->except_selected)
gotone += s->except_ready = true;
return gotone;
}
ssize_t n = pipe_data_available (s->fd, fh, h, PDA_SELECT | PDA_WRITE);
select_printf ("write: %s, n %d", fh->get_name (), n);
gotone += s->write_ready = (n >= PIPE_BUF);
if (n < 0 && s->except_selected)
gotone += s->except_ready = true;
}
return gotone;
}
static int start_thread_pipe (select_record *me, select_stuff *stuff);
static DWORD
thread_pipe (void *arg)
{
select_pipe_info *pi = (select_pipe_info *) arg;
DWORD sleep_time = 0;
bool looping = true;
while (looping)
{
for (select_record *s = pi->start; (s = s->next); )
if (s->startup == start_thread_pipe)
{
if (peek_pipe (s, true))
looping = false;
if (pi->stop_thread)
{
select_printf ("stopping");
looping = false;
break;
}
}
if (!looping)
break;
cygwait (pi->bye, sleep_time >> 3);
if (sleep_time < 80)
++sleep_time;
if (pi->stop_thread)
break;
}
return 0;
}
static int
start_thread_pipe (select_record *me, select_stuff *stuff)
{
select_pipe_info *pi = stuff->device_specific_pipe;
if (pi->start)
me->h = *((select_pipe_info *) stuff->device_specific_pipe)->thread;
else
{
pi->start = &stuff->start;
pi->stop_thread = false;
pi->bye = me->fh->get_select_sem ();
if (pi->bye)
DuplicateHandle (GetCurrentProcess (), pi->bye,
GetCurrentProcess (), &pi->bye,
0, 0, DUPLICATE_SAME_ACCESS);
else
pi->bye = CreateSemaphore (&sec_none_nih, 0, INT32_MAX, NULL);
pi->thread = new cygthread (thread_pipe, pi, "pipesel");
me->h = *pi->thread;
if (!me->h)
return 0;
}
return 1;
}
static void
pipe_cleanup (select_record *, select_stuff *stuff)
{
select_pipe_info *pi = (select_pipe_info *) stuff->device_specific_pipe;
if (!pi)
return;
if (pi->thread)
{
pi->stop_thread = true;
ReleaseSemaphore (pi->bye, get_obj_handle_count (pi->bye), NULL);
pi->thread->detach ();
CloseHandle (pi->bye);
}
delete pi;
stuff->device_specific_pipe = NULL;
}
select_record *
fhandler_pipe::select_read (select_stuff *ss)
{
if (!ss->device_specific_pipe
&& (ss->device_specific_pipe = new select_pipe_info) == NULL)
return NULL;
select_record *s = ss->start.next;
s->startup = start_thread_pipe;
s->peek = peek_pipe;
s->verify = verify_ok;
s->cleanup = pipe_cleanup;
s->read_selected = true;
s->read_ready = false;
return s;
}
select_record *
fhandler_pipe::select_write (select_stuff *ss)
{
if (!ss->device_specific_pipe
&& (ss->device_specific_pipe = new select_pipe_info) == NULL)
return NULL;
select_record *s = ss->start.next;
s->startup = start_thread_pipe;
s->peek = peek_pipe;
s->verify = verify_ok;
s->cleanup = pipe_cleanup;
s->write_selected = true;
s->write_ready = false;
return s;
}
select_record *
fhandler_pipe::select_except (select_stuff *ss)
{
if (!ss->device_specific_pipe
&& (ss->device_specific_pipe = new select_pipe_info) == NULL)
return NULL;
select_record *s = ss->start.next;
s->startup = start_thread_pipe;
s->peek = peek_pipe;
s->verify = verify_ok;
s->cleanup = pipe_cleanup;
s->except_selected = true;
s->except_ready = false;
return s;
}
static int
peek_fifo (select_record *s, bool from_select)
{
if (cygheap->fdtab.not_open (s->fd))
{
s->thread_errno = EBADF;
return -1;
}
int gotone = 0;
fhandler_fifo *fh = (fhandler_fifo *) s->fh;
if (s->read_selected)
{
if (s->read_ready)
{
select_printf ("%s, already ready for read", fh->get_name ());
gotone = 1;
goto out;
}
if (fh->get_readahead_valid ())
{
select_printf ("readahead");
gotone = s->read_ready = true;
goto out;
}
fh->reading_lock ();
if (fh->take_ownership (1) < 0)
{
fh->reading_unlock ();
goto out;
}
fh->fifo_client_lock ();
int nconnected = 0;
for (int i = 0; i < fh->get_nhandlers (); i++)
{
fifo_client_handler &fc = fh->get_fc_handler (i);
fifo_client_connect_state prev_state = fc.query_and_set_state ();
if (fc.get_state () >= fc_connected)
{
nconnected++;
if (prev_state == fc_listening)
/* The connection was not recorded by the fifo_reader_thread. */
fh->record_connection (fc, false);
if (fc.get_state () == fc_input_avail)
{
select_printf ("read: %s, ready for read", fh->get_name ());
fh->fifo_client_unlock ();
fh->reading_unlock ();
gotone += s->read_ready = true;
goto out;
}
}
}
fh->fifo_client_unlock ();
/* According to POSIX and the Linux man page, we're supposed to
report read ready if the FIFO is at EOF, i.e., if the pipe is
empty and there are no writers. But there seems to be an
undocumented exception, observed on Linux and other platforms
(https://cygwin.com/pipermail/cygwin/2022-September/252223.html):
If no writer has ever been opened, then we do not report read
ready. This can happen if a reader is opened with O_NONBLOCK
before any writers have opened. To be consistent with other
platforms, we use a special EOF test that returns false if
there's never been a writer opened. */
if (!nconnected && fh->select_hit_eof ())
{
select_printf ("read: %s, saw EOF", fh->get_name ());
gotone += s->read_ready = true;
if (s->except_selected)
gotone += s->except_ready = true;
}
fh->reading_unlock ();
}
out:
if (s->write_selected)
{
ssize_t n = pipe_data_available (s->fd, fh, fh->get_handle (),
PDA_SELECT | PDA_WRITE);
select_printf ("write: %s, n %d", fh->get_name (), n);
gotone += s->write_ready = (n >= PIPE_BUF);
if (n < 0 && s->except_selected)
gotone += s->except_ready = true;
}
return gotone;
}
static int start_thread_fifo (select_record *me, select_stuff *stuff);