select.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /* Emulation for select(2)
  2. Contributed by Paolo Bonzini.
  3. Copyright 2008-2014 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. /* Optimized test whether a HANDLE refers to a console.
  67. See <http://lists.gnu.org/archive/html/bug-gnulib/2009-08/msg00065.html>. */
  68. #define IsConsoleHandle(h) (((intptr_t) (h) & 3) == 3)
  69. static BOOL
  70. IsSocketHandle (HANDLE h)
  71. {
  72. WSANETWORKEVENTS ev;
  73. if (IsConsoleHandle (h))
  74. return FALSE;
  75. /* Under Wine, it seems that getsockopt returns 0 for pipes too.
  76. WSAEnumNetworkEvents instead distinguishes the two correctly. */
  77. ev.lNetworkEvents = 0xDEADBEEF;
  78. WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
  79. return ev.lNetworkEvents != 0xDEADBEEF;
  80. }
  81. /* Compute output fd_sets for libc descriptor FD (whose Windows handle is
  82. H). */
  83. static int
  84. windows_poll_handle (HANDLE h, int fd,
  85. struct bitset *rbits,
  86. struct bitset *wbits,
  87. struct bitset *xbits)
  88. {
  89. BOOL read, write, except;
  90. int i, ret;
  91. INPUT_RECORD *irbuffer;
  92. DWORD avail, nbuffer;
  93. BOOL bRet;
  94. IO_STATUS_BLOCK iosb;
  95. FILE_PIPE_LOCAL_INFORMATION fpli;
  96. static PNtQueryInformationFile NtQueryInformationFile;
  97. static BOOL once_only;
  98. read = write = except = FALSE;
  99. switch (GetFileType (h))
  100. {
  101. case FILE_TYPE_DISK:
  102. read = TRUE;
  103. write = TRUE;
  104. break;
  105. case FILE_TYPE_PIPE:
  106. if (!once_only)
  107. {
  108. NtQueryInformationFile = (PNtQueryInformationFile)
  109. GetProcAddress (GetModuleHandle ("ntdll.dll"),
  110. "NtQueryInformationFile");
  111. once_only = TRUE;
  112. }
  113. if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
  114. {
  115. if (avail)
  116. read = TRUE;
  117. }
  118. else if (GetLastError () == ERROR_BROKEN_PIPE)
  119. ;
  120. else
  121. {
  122. /* It was the write-end of the pipe. Check if it is writable.
  123. If NtQueryInformationFile fails, optimistically assume the pipe is
  124. writable. This could happen on Windows 9x, where
  125. NtQueryInformationFile is not available, or if we inherit a pipe
  126. that doesn't permit FILE_READ_ATTRIBUTES access on the write end
  127. (I think this should not happen since Windows XP SP2; WINE seems
  128. fine too). Otherwise, ensure that enough space is available for
  129. atomic writes. */
  130. memset (&iosb, 0, sizeof (iosb));
  131. memset (&fpli, 0, sizeof (fpli));
  132. if (!NtQueryInformationFile
  133. || NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
  134. FilePipeLocalInformation)
  135. || fpli.WriteQuotaAvailable >= PIPE_BUF
  136. || (fpli.OutboundQuota < PIPE_BUF &&
  137. fpli.WriteQuotaAvailable == fpli.OutboundQuota))
  138. write = TRUE;
  139. }
  140. break;
  141. case FILE_TYPE_CHAR:
  142. write = TRUE;
  143. if (!(rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
  144. break;
  145. ret = WaitForSingleObject (h, 0);
  146. if (ret == WAIT_OBJECT_0)
  147. {
  148. if (!IsConsoleHandle (h))
  149. {
  150. read = TRUE;
  151. break;
  152. }
  153. nbuffer = avail = 0;
  154. bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
  155. /* Screen buffers handles are filtered earlier. */
  156. assert (bRet);
  157. if (nbuffer == 0)
  158. {
  159. except = TRUE;
  160. break;
  161. }
  162. irbuffer = (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
  163. bRet = PeekConsoleInput (h, irbuffer, nbuffer, &avail);
  164. if (!bRet || avail == 0)
  165. {
  166. except = TRUE;
  167. break;
  168. }
  169. for (i = 0; i < avail; i++)
  170. if (irbuffer[i].EventType == KEY_EVENT)
  171. read = TRUE;
  172. }
  173. break;
  174. default:
  175. ret = WaitForSingleObject (h, 0);
  176. write = TRUE;
  177. if (ret == WAIT_OBJECT_0)
  178. read = TRUE;
  179. break;
  180. }
  181. ret = 0;
  182. if (read && (rbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
  183. {
  184. rbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
  185. ret++;
  186. }
  187. if (write && (wbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
  188. {
  189. wbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
  190. ret++;
  191. }
  192. if (except && (xbits->in[fd / CHAR_BIT] & (1 << (fd & (CHAR_BIT - 1)))))
  193. {
  194. xbits->out[fd / CHAR_BIT] |= (1 << (fd & (CHAR_BIT - 1)));
  195. ret++;
  196. }
  197. return ret;
  198. }
  199. int
  200. rpl_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *xfds,
  201. struct timeval *timeout)
  202. #undef timeval
  203. {
  204. static struct timeval tv0;
  205. static HANDLE hEvent;
  206. HANDLE h, handle_array[FD_SETSIZE + 2];
  207. fd_set handle_rfds, handle_wfds, handle_xfds;
  208. struct bitset rbits, wbits, xbits;
  209. unsigned char anyfds_in[FD_SETSIZE / CHAR_BIT];
  210. DWORD ret, wait_timeout, nhandles, nsock, nbuffer;
  211. MSG msg;
  212. int i, fd, rc;
  213. if (nfds > FD_SETSIZE)
  214. nfds = FD_SETSIZE;
  215. if (!timeout)
  216. wait_timeout = INFINITE;
  217. else
  218. {
  219. wait_timeout = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
  220. /* select is also used as a portable usleep. */
  221. if (!rfds && !wfds && !xfds)
  222. {
  223. Sleep (wait_timeout);
  224. return 0;
  225. }
  226. }
  227. if (!hEvent)
  228. hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
  229. handle_array[0] = hEvent;
  230. nhandles = 1;
  231. nsock = 0;
  232. /* Copy descriptors to bitsets. At the same time, eliminate
  233. bits in the "wrong" direction for console input buffers
  234. and screen buffers, because screen buffers are waitable
  235. and they will block until a character is available. */
  236. memset (&rbits, 0, sizeof (rbits));
  237. memset (&wbits, 0, sizeof (wbits));
  238. memset (&xbits, 0, sizeof (xbits));
  239. memset (anyfds_in, 0, sizeof (anyfds_in));
  240. if (rfds)
  241. for (i = 0; i < rfds->fd_count; i++)
  242. {
  243. fd = rfds->fd_array[i];
  244. h = (HANDLE) _get_osfhandle (fd);
  245. if (IsConsoleHandle (h)
  246. && !GetNumberOfConsoleInputEvents (h, &nbuffer))
  247. continue;
  248. rbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
  249. anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
  250. }
  251. else
  252. rfds = (fd_set *) alloca (sizeof (fd_set));
  253. if (wfds)
  254. for (i = 0; i < wfds->fd_count; i++)
  255. {
  256. fd = wfds->fd_array[i];
  257. h = (HANDLE) _get_osfhandle (fd);
  258. if (IsConsoleHandle (h)
  259. && GetNumberOfConsoleInputEvents (h, &nbuffer))
  260. continue;
  261. wbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
  262. anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
  263. }
  264. else
  265. wfds = (fd_set *) alloca (sizeof (fd_set));
  266. if (xfds)
  267. for (i = 0; i < xfds->fd_count; i++)
  268. {
  269. fd = xfds->fd_array[i];
  270. xbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
  271. anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
  272. }
  273. else
  274. xfds = (fd_set *) alloca (sizeof (fd_set));
  275. /* Zero all the fd_sets, including the application's. */
  276. FD_ZERO (rfds);
  277. FD_ZERO (wfds);
  278. FD_ZERO (xfds);
  279. FD_ZERO (&handle_rfds);
  280. FD_ZERO (&handle_wfds);
  281. FD_ZERO (&handle_xfds);
  282. /* Classify handles. Create fd sets for sockets, poll the others. */
  283. for (i = 0; i < nfds; i++)
  284. {
  285. if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
  286. continue;
  287. h = (HANDLE) _get_osfhandle (i);
  288. if (!h)
  289. {
  290. errno = EBADF;
  291. return -1;
  292. }
  293. if (IsSocketHandle (h))
  294. {
  295. int requested = FD_CLOSE;
  296. /* See above; socket handles are mapped onto select, but we
  297. need to map descriptors to handles. */
  298. if (rbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
  299. {
  300. requested |= FD_READ | FD_ACCEPT;
  301. FD_SET ((SOCKET) h, rfds);
  302. FD_SET ((SOCKET) h, &handle_rfds);
  303. }
  304. if (wbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
  305. {
  306. requested |= FD_WRITE | FD_CONNECT;
  307. FD_SET ((SOCKET) h, wfds);
  308. FD_SET ((SOCKET) h, &handle_wfds);
  309. }
  310. if (xbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
  311. {
  312. requested |= FD_OOB;
  313. FD_SET ((SOCKET) h, xfds);
  314. FD_SET ((SOCKET) h, &handle_xfds);
  315. }
  316. WSAEventSelect ((SOCKET) h, hEvent, requested);
  317. nsock++;
  318. }
  319. else
  320. {
  321. handle_array[nhandles++] = h;
  322. /* Poll now. If we get an event, do not wait below. */
  323. if (wait_timeout != 0
  324. && windows_poll_handle (h, i, &rbits, &wbits, &xbits))
  325. wait_timeout = 0;
  326. }
  327. }
  328. /* Place a sentinel at the end of the array. */
  329. handle_array[nhandles] = NULL;
  330. restart:
  331. if (wait_timeout == 0 || nsock == 0)
  332. rc = 0;
  333. else
  334. {
  335. /* See if we need to wait in the loop below. If any select is ready,
  336. do MsgWaitForMultipleObjects anyway to dispatch messages, but
  337. no need to call select again. */
  338. rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);
  339. if (rc == 0)
  340. {
  341. /* Restore the fd_sets for the other select we do below. */
  342. memcpy (&handle_rfds, rfds, sizeof (fd_set));
  343. memcpy (&handle_wfds, wfds, sizeof (fd_set));
  344. memcpy (&handle_xfds, xfds, sizeof (fd_set));
  345. }
  346. else
  347. wait_timeout = 0;
  348. }
  349. for (;;)
  350. {
  351. ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
  352. wait_timeout, QS_ALLINPUT);
  353. if (ret == WAIT_OBJECT_0 + nhandles)
  354. {
  355. /* new input of some other kind */
  356. BOOL bRet;
  357. while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
  358. {
  359. TranslateMessage (&msg);
  360. DispatchMessage (&msg);
  361. }
  362. }
  363. else
  364. break;
  365. }
  366. /* If we haven't done it yet, check the status of the sockets. */
  367. if (rc == 0 && nsock > 0)
  368. rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);
  369. if (nhandles > 1)
  370. {
  371. /* Count results that are not counted in the return value of select. */
  372. nhandles = 1;
  373. for (i = 0; i < nfds; i++)
  374. {
  375. if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
  376. continue;
  377. h = (HANDLE) _get_osfhandle (i);
  378. if (h == handle_array[nhandles])
  379. {
  380. /* Not a socket. */
  381. nhandles++;
  382. windows_poll_handle (h, i, &rbits, &wbits, &xbits);
  383. if (rbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))
  384. || wbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))
  385. || xbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
  386. rc++;
  387. }
  388. }
  389. if (rc == 0 && wait_timeout == INFINITE)
  390. {
  391. /* Sleep 1 millisecond to avoid busy wait and retry with the
  392. original fd_sets. */
  393. memcpy (&handle_rfds, rfds, sizeof (fd_set));
  394. memcpy (&handle_wfds, wfds, sizeof (fd_set));
  395. memcpy (&handle_xfds, xfds, sizeof (fd_set));
  396. SleepEx (1, TRUE);
  397. goto restart;
  398. }
  399. }
  400. /* Now fill in the results. */
  401. FD_ZERO (rfds);
  402. FD_ZERO (wfds);
  403. FD_ZERO (xfds);
  404. nhandles = 1;
  405. for (i = 0; i < nfds; i++)
  406. {
  407. if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
  408. continue;
  409. h = (HANDLE) _get_osfhandle (i);
  410. if (h != handle_array[nhandles])
  411. {
  412. /* Perform handle->descriptor mapping. */
  413. WSAEventSelect ((SOCKET) h, NULL, 0);
  414. if (FD_ISSET (h, &handle_rfds))
  415. FD_SET (i, rfds);
  416. if (FD_ISSET (h, &handle_wfds))
  417. FD_SET (i, wfds);
  418. if (FD_ISSET (h, &handle_xfds))
  419. FD_SET (i, xfds);
  420. }
  421. else
  422. {
  423. /* Not a socket. */
  424. nhandles++;
  425. if (rbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
  426. FD_SET (i, rfds);
  427. if (wbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
  428. FD_SET (i, wfds);
  429. if (xbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
  430. FD_SET (i, xfds);
  431. }
  432. }
  433. return rc;
  434. }
  435. #else /* ! Native Windows. */
  436. #include <sys/select.h>
  437. #include <stddef.h> /* NULL */
  438. #include <errno.h>
  439. #include <unistd.h>
  440. #undef select
  441. int
  442. rpl_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *xfds,
  443. struct timeval *timeout)
  444. {
  445. int i;
  446. /* FreeBSD 8.2 has a bug: it does not always detect invalid fds. */
  447. if (nfds < 0 || nfds > FD_SETSIZE)
  448. {
  449. errno = EINVAL;
  450. return -1;
  451. }
  452. for (i = 0; i < nfds; i++)
  453. {
  454. if (((rfds && FD_ISSET (i, rfds))
  455. || (wfds && FD_ISSET (i, wfds))
  456. || (xfds && FD_ISSET (i, xfds)))
  457. && dup2 (i, i) != i)
  458. return -1;
  459. }
  460. /* Interix 3.5 has a bug: it does not support nfds == 0. */
  461. if (nfds == 0)
  462. {
  463. nfds = 1;
  464. rfds = NULL;
  465. wfds = NULL;
  466. xfds = NULL;
  467. }
  468. return select (nfds, rfds, wfds, xfds, timeout);
  469. }
  470. #endif