select.c 16 KB

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