Debian Codegraph @

lib/select.c

raw
1 /* Emulation for select(2)
2 Contributed by Paolo Bonzini.
3
4 Copyright 2008-2026 Free Software Foundation, Inc.
5
6 This file is part of gnulib.
7
8 This file is free software: you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as
10 published by the Free Software Foundation; either version 2.1 of the
11 License, or (at your option) any later version.
12
13 This file is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20
21 #include <config.h>
22
23 /* Specification. */
24 #include <sys/select.h>
25
26 #if defined _WIN32 && ! defined __CYGWIN__
27 /* Native Windows. */
28
29 #include <alloca.h>
30 #include <assert.h>
31 #include <sys/types.h>
32 #include <errno.h>
33 #include <limits.h>
34
35 #include <winsock2.h>
36 #include <windows.h>
37 #include <io.h>
38 #include <stdio.h>
39 #include <conio.h>
40 #include <time.h>
41
42 /* Get the overridden 'struct timeval'. */
43 #include <sys/time.h>
44
45 #if GNULIB_MSVC_NOTHROW
46 # include "msvc-nothrow.h"
47 #else
48 # include <io.h>
49 #endif
50
51 #undef select
52
53 /* Don't assume that UNICODE is not defined. */
54 #undef GetModuleHandle
55 #define GetModuleHandle GetModuleHandleA
56 #undef PeekConsoleInput
57 #define PeekConsoleInput PeekConsoleInputA
58 #undef CreateEvent
59 #define CreateEvent CreateEventA
60 #undef PeekMessage
61 #define PeekMessage PeekMessageA
62 #undef DispatchMessage
63 #define DispatchMessage DispatchMessageA
64
65 /* Avoid warnings from gcc -Wcast-function-type. */
66 #define GetProcAddress \
67 (void *) GetProcAddress
68
69 struct bitset {
70 unsigned char in[FD_SETSIZE / CHAR_BIT];
71 unsigned char out[FD_SETSIZE / CHAR_BIT];
72 };
73
74 /* Declare data structures for ntdll functions. */
75 typedef struct _FILE_PIPE_LOCAL_INFORMATION {
76 ULONG NamedPipeType;
77 ULONG NamedPipeConfiguration;
78 ULONG MaximumInstances;
79 ULONG CurrentInstances;
80 ULONG InboundQuota;
81 ULONG ReadDataAvailable;
82 ULONG OutboundQuota;
83 ULONG WriteQuotaAvailable;
84 ULONG NamedPipeState;
85 ULONG NamedPipeEnd;
86 } FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION;
87
88 typedef struct _IO_STATUS_BLOCK
89 {
90 union {
91 DWORD Status;
92 PVOID Pointer;
93 } u;
94 ULONG_PTR Information;
95 } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
96
97 typedef enum _FILE_INFORMATION_CLASS {
98 FilePipeLocalInformation = 24
99 } FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
100
101 typedef DWORD (WINAPI *PNtQueryInformationFile)
102 (HANDLE, IO_STATUS_BLOCK *, VOID *, ULONG, FILE_INFORMATION_CLASS);
103
104 #ifndef PIPE_BUF
105 #define PIPE_BUF 512
106 #endif
107
108 static BOOL IsConsoleHandle (HANDLE h)
109 {
110 DWORD mode;
111 return GetConsoleMode (h, &mode) != 0;
112 }
113
114 static BOOL
115 IsSocketHandle (HANDLE h)
116 {
117 if (IsConsoleHandle (h))
118 return FALSE;
119
120 /* Under Wine, it seems that getsockopt returns 0 for pipes too.
121 WSAEnumNetworkEvents instead distinguishes the two correctly. */
122 WSANETWORKEVENTS ev;
123 ev.lNetworkEvents = 0xDEADBEEF;
124 WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
125 return ev.lNetworkEvents != 0xDEADBEEF;
126 }
127
128 /* Compute output fd_sets for libc descriptor FD (whose Windows handle is
129 H). */
130
131 static int
132 windows_poll_handle (HANDLE h, int fd,
133 struct bitset *rbits,
134 struct bitset *wbits,
135 struct bitset *xbits)
136 {
137 static PNtQueryInformationFile NtQueryInformationFile;
138 static BOOL once_only;
139
140 BOOL read = FALSE;
141 BOOL write = FALSE;
142 BOOL except = FALSE;
143 switch (GetFileType (h))
144 {
145 case FILE_TYPE_DISK:
146 read = TRUE;
147 write = TRUE;
148 break;
149
150 case FILE_TYPE_PIPE:
151 if (!once_only)
152 {
153 NtQueryInformationFile = (PNtQueryInformationFile)
154 GetProcAddress (GetModuleHandle ("ntdll.dll"),
155 "NtQueryInformationFile");
156 once_only = TRUE;
157 }
158
159 DWORD avail;
160 if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
161 {
162 if (avail)
163 read = TRUE;
164 }
165 else if (GetLastError () == ERROR_BROKEN_PIPE)
166 ;
167 else
168 {
169 /* It was the write-end of the pipe. Check if it is writable.
170 If NtQueryInformationFile fails, optimistically assume the pipe is
171 writable. This could happen on Windows 9x, where
172 NtQueryInformationFile is not available, or if we inherit a pipe
173 that doesn't permit FILE_READ_ATTRIBUTES access on the write end
174 (I think this should not happen since Windows XP SP2; WINE seems
175 fine too). Otherwise, ensure that enough space is available for
176 atomic writes. */
177 IO_STATUS_BLOCK iosb;
178 memset (&iosb, 0, sizeof (iosb));
179 FILE_PIPE_LOCAL_INFORMATION fpli;
180 memset (&fpli, 0, sizeof (fpli));
181
182 if (!NtQueryInformationFile
183 || NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
184 FilePipeLocalInformation)
185 || fpli.WriteQuotaAvailable >= PIPE_BUF
186 || (fpli.OutboundQuota < PIPE_BUF &&
187 fpli.WriteQuotaAvailable == fpli.OutboundQuota))
188 write = TRUE;
189 }
190 break;
191
192 case FILE_TYPE_CHAR:
193 write = TRUE;
194 if (!(rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
195 break;
196
197 if (WaitForSingleObject (h, 0) == WAIT_OBJECT_0)
198 {
199 if (!IsConsoleHandle (h))
200 {
201 read = TRUE;
202 break;
203 }
204
205 DWORD nbuffer = 0;
206 BOOL bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
207 /* Screen buffers handles are filtered earlier. */
208 assert (bRet);
209 if (nbuffer == 0)
210 {
211 except = TRUE;
212 break;
213 }
214
215 INPUT_RECORD *irbuffer =
216 (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
217 DWORD avail = 0;
218 if (! PeekConsoleInput (h, irbuffer, nbuffer, &avail) || avail == 0)
219 {
220 except = TRUE;
221 break;
222 }
223
224 for (int i = 0; i < avail; i++)
225 if (irbuffer[i].EventType == KEY_EVENT)
226 read = TRUE;
227 }
228 break;
229
230 default:
231 {
232 int ret = WaitForSingleObject (h, 0);
233 write = TRUE;
234 if (ret == WAIT_OBJECT_0)
235 read = TRUE;
236 }
237 break;
238 }
239
240 int ret = 0;
241 if (read && (rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
242 {
243 rbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
244 ret++;
245 }
246
247 if (write && (wbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
248 {
249 wbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
250 ret++;
251 }
252
253 if (except && (xbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
254 {
255 xbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
256 ret++;
257 }
258
259 return ret;
260 }
261
262 int
263 rpl_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *xfds,
264 struct timeval *timeout)
265 #undef timeval
266 {
267 static struct timeval tv0;
268 static HANDLE hEvent;
269
270 if (nfds < 0 || nfds > FD_SETSIZE)
271 {
272 errno = EINVAL;
273 return -1;
274 }
275
276 DWORD wait_timeout;
277 if (!timeout)
278 wait_timeout = INFINITE;
279 else
280 {
281 wait_timeout = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
282
283 /* select is also used as a portable usleep. */
284 if (!rfds && !wfds && !xfds)
285 {
286 Sleep (wait_timeout);
287 return 0;
288 }
289 }
290
291 if (!hEvent)
292 hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
293
294 /* Copy descriptors to bitsets. At the same time, eliminate
295 bits in the "wrong" direction for console input buffers
296 and screen buffers, because screen buffers are waitable
297 and they will block until a character is available. */
298 struct bitset rbits;
299 memset (&rbits, 0, sizeof (rbits));
300 struct bitset wbits;
301 memset (&wbits, 0, sizeof (wbits));
302 struct bitset xbits;
303 memset (&xbits, 0, sizeof (xbits));
304 unsigned char anyfds_in[FD_SETSIZE / CHAR_BIT];
305 memset (anyfds_in, 0, sizeof (anyfds_in));
306 if (rfds)
307 for (int i = 0; i < rfds->fd_count; i++)
308 {
309 int fd = rfds->fd_array[i];
310 HANDLE h = (HANDLE) _get_osfhandle (fd);
311 DWORD nbuffer;
312 if (!IsConsoleHandle (h)
313 || GetNumberOfConsoleInputEvents (h, &nbuffer))
314 {
315 rbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
316 anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
317 }
318 }
319 else
320 rfds = (fd_set *) alloca (sizeof (fd_set));
321
322 if (wfds)
323 for (int i = 0; i < wfds->fd_count; i++)
324 {
325 int fd = wfds->fd_array[i];
326 HANDLE h = (HANDLE) _get_osfhandle (fd);
327 DWORD nbuffer;
328 if (!IsConsoleHandle (h)
329 || !GetNumberOfConsoleInputEvents (h, &nbuffer))
330 {
331 wbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
332 anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
333 }
334 }
335 else
336 wfds = (fd_set *) alloca (sizeof (fd_set));
337
338 if (xfds)
339 for (int i = 0; i < xfds->fd_count; i++)
340 {
341 int fd = xfds->fd_array[i];
342 xbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
343 anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
344 }
345 else
346 xfds = (fd_set *) alloca (sizeof (fd_set));
347
348 /* Zero all the fd_sets, including the application's. */
349 FD_ZERO (rfds);
350 FD_ZERO (wfds);
351 FD_ZERO (xfds);
352 fd_set handle_rfds;
353 FD_ZERO (&handle_rfds);
354 fd_set handle_wfds;
355 FD_ZERO (&handle_wfds);
356 fd_set handle_xfds;
357 FD_ZERO (&handle_xfds);
358
359 HANDLE handle_array[FD_SETSIZE + 2];
360 handle_array[0] = hEvent;
361 DWORD nhandles = 1;
362 DWORD nsock = 0;
363
364 /* Classify handles. Create fd sets for sockets, poll the others. */
365 for (int i = 0; i < nfds; i++)
366 {
367 if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) != 0)
368 {
369 HANDLE h = (HANDLE) _get_osfhandle (i);
370 if (!h)
371 {
372 errno = EBADF;
373 return -1;
374 }
375
376 if (IsSocketHandle (h))
377 {
378 int requested = FD_CLOSE;
379
380 /* See above; socket handles are mapped onto select, but we
381 need to map descriptors to handles. */
382 if (rbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
383 {
384 requested |= FD_READ | FD_ACCEPT;
385 FD_SET ((SOCKET) h, rfds);
386 FD_SET ((SOCKET) h, &handle_rfds);
387 }
388 if (wbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
389 {
390 requested |= FD_WRITE | FD_CONNECT;
391 FD_SET ((SOCKET) h, wfds);
392 FD_SET ((SOCKET) h, &handle_wfds);
393 }
394 if (xbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
395 {
396 requested |= FD_OOB;
397 FD_SET ((SOCKET) h, xfds);
398 FD_SET ((SOCKET) h, &handle_xfds);
399 }
400
401 WSAEventSelect ((SOCKET) h, hEvent, requested);
402 nsock++;
403 }
404 else
405 {
406 handle_array[nhandles++] = h;
407
408 /* Poll now. If we get an event, do not wait below. */
409 if (wait_timeout != 0
410 && windows_poll_handle (h, i, &rbits, &wbits, &xbits))
411 wait_timeout = 0;
412 }
413 }
414 }
415
416 /* Place a sentinel at the end of the array. */
417 handle_array[nhandles] = NULL;
418
419 /* When will the waiting period expire? */
420 clock_t tend;
421 if (wait_timeout != INFINITE)
422 tend = clock () + wait_timeout;
423
424 restart: ;
425 int rc;
426 if (wait_timeout == 0 || nsock == 0)
427 rc = 0;
428 else
429 {
430 /* See if we need to wait in the loop below. If any select is ready,
431 do MsgWaitForMultipleObjects anyway to dispatch messages, but
432 no need to call select again. */
433 rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);
434 if (rc == 0)
435 {
436 /* Restore the fd_sets for the other select we do below. */
437 memcpy (&handle_rfds, rfds, sizeof (fd_set));
438 memcpy (&handle_wfds, wfds, sizeof (fd_set));
439 memcpy (&handle_xfds, xfds, sizeof (fd_set));
440 }
441 else
442 wait_timeout = 0;
443 }
444
445 /* How much is left to wait? */
446 if (wait_timeout != INFINITE)
447 {
448 clock_t tnow = clock ();
449 if (tend >= tnow)
450 wait_timeout = tend - tnow;
451 else
452 wait_timeout = 0;
453 }
454
455 for (;;)
456 {
457 DWORD ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
458 wait_timeout, QS_ALLINPUT);
459
460 if (ret == WAIT_OBJECT_0 + nhandles)
461 {
462 /* new input of some other kind */
463 MSG msg;
464 while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE) != 0)
465 {
466 TranslateMessage (&msg);
467 DispatchMessage (&msg);
468 }
469 }
470 else
471 break;
472 }
473
474 /* If we haven't done it yet, check the status of the sockets. */
475 if (rc == 0 && nsock > 0)
476 rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);
477
478 if (nhandles > 1)
479 {
480 /* Count results that are not counted in the return value of select. */
481 nhandles = 1;
482 for (int i = 0; i < nfds; i++)
483 {
484 if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) != 0)
485 {
486 HANDLE h = (HANDLE) _get_osfhandle (i);
487 if (h == handle_array[nhandles])
488 {
489 /* Not a socket. */
490 nhandles++;
491 windows_poll_handle (h, i, &rbits, &wbits, &xbits);
492 if (rbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))
493 || wbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))
494 || xbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
495 rc++;
496 }
497 }
498 }
499
500 if (rc == 0
501 && (wait_timeout == INFINITE
502 /* If NHANDLES > 1, but no bits are set, it means we've
503 been told incorrectly that some handle was signaled.
504 This happens with anonymous pipes, which always cause
505 MsgWaitForMultipleObjects to exit immediately, but no
506 data is found ready to be read by windows_poll_handle.
507 To avoid a total failure (whereby we return zero and
508 don't wait at all), let's poll in a more busy loop. */
509 || (wait_timeout != 0 && nhandles > 1)))
510 {
511 /* Sleep 1 millisecond to avoid busy wait and retry with the
512 original fd_sets. */
513 memcpy (&handle_rfds, rfds, sizeof (fd_set));
514 memcpy (&handle_wfds, wfds, sizeof (fd_set));
515 memcpy (&handle_xfds, xfds, sizeof (fd_set));
516 SleepEx (1, TRUE);
517 goto restart;
518 }
519 if (timeout && wait_timeout == 0 && rc == 0)
520 timeout->tv_sec = timeout->tv_usec = 0;
521 }
522
523 /* Now fill in the results. */
524 FD_ZERO (rfds);
525 FD_ZERO (wfds);
526 FD_ZERO (xfds);
527 nhandles = 1;
528 for (int i = 0; i < nfds; i++)
529 {
530 if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) != 0)
531 {
532 HANDLE h = (HANDLE) _get_osfhandle (i);
533 if (h != handle_array[nhandles])
534 {
535 /* Perform handle->descriptor mapping. */
536 SOCKET s = (SOCKET) h;
537 WSAEventSelect (s, NULL, 0);
538 if (FD_ISSET (s, &handle_rfds))
539 FD_SET (i, rfds);
540 if (FD_ISSET (s, &handle_wfds))
541 FD_SET (i, wfds);
542 if (FD_ISSET (s, &handle_xfds))
543 FD_SET (i, xfds);
544 }
545 else
546 {
547 /* Not a socket. */
548 nhandles++;
549 if (rbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
550 FD_SET (i, rfds);
551 if (wbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
552 FD_SET (i, wfds);
553 if (xbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
554 FD_SET (i, xfds);
555 }
556 }
557 }
558
559 return rc;
560 }
561
562 #else /* ! Native Windows. */
563
564 #include <stddef.h> /* NULL */
565 #include <errno.h>
566 #include <unistd.h>
567
568 #undef select
569
570 int
571 rpl_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *xfds,
572 struct timeval *timeout)
573 {
574 /* FreeBSD 8.2 has a bug: it does not always detect invalid fds. */
575 if (nfds < 0 || nfds > FD_SETSIZE)
576 {
577 errno = EINVAL;
578 return -1;
579 }
580 for (int i = 0; i < nfds; i++)
581 {
582 if (((rfds && FD_ISSET (i, rfds))
583 || (wfds && FD_ISSET (i, wfds))
584 || (xfds && FD_ISSET (i, xfds)))
585 && dup2 (i, i) != i)
586 return -1;
587 }
588
589 /* Interix 3.5 has a bug: it does not support nfds == 0. */
590 if (nfds == 0)
591 {
592 nfds = 1;
593 rfds = NULL;
594 wfds = NULL;
595 xfds = NULL;
596 }
597 return select (nfds, rfds, wfds, xfds, timeout);
598 }
599
600 #endif