select.c 16 KB

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