PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/gl/poll.c

#
C | 607 lines | 452 code | 82 blank | 73 comment | 144 complexity | f0e0324b45ed30b0313c5c78ba3548c4 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, LGPL-2.0
  1. /* Emulation for poll(2)
  2. Contributed by Paolo Bonzini.
  3. Copyright 2001-2003, 2006-2012 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 <http://www.gnu.org/licenses/>. */
  15. /* Tell gcc not to warn about the (nfd < 0) tests, below. */
  16. #if (__GNUC__ == 4 && 3 <= __GNUC_MINOR__) || 4 < __GNUC__
  17. # pragma GCC diagnostic ignored "-Wtype-limits"
  18. #endif
  19. #include <config.h>
  20. #include <alloca.h>
  21. #include <sys/types.h>
  22. /* Specification. */
  23. #include <poll.h>
  24. #include <errno.h>
  25. #include <limits.h>
  26. #include <assert.h>
  27. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  28. # define WINDOWS_NATIVE
  29. # include <winsock2.h>
  30. # include <windows.h>
  31. # include <io.h>
  32. # include <stdio.h>
  33. # include <conio.h>
  34. # include "msvc-nothrow.h"
  35. #else
  36. # include <sys/time.h>
  37. # include <sys/socket.h>
  38. # include <sys/select.h>
  39. # include <unistd.h>
  40. #endif
  41. #ifdef HAVE_SYS_IOCTL_H
  42. # include <sys/ioctl.h>
  43. #endif
  44. #ifdef HAVE_SYS_FILIO_H
  45. # include <sys/filio.h>
  46. #endif
  47. #include <time.h>
  48. #ifndef INFTIM
  49. # define INFTIM (-1)
  50. #endif
  51. /* BeOS does not have MSG_PEEK. */
  52. #ifndef MSG_PEEK
  53. # define MSG_PEEK 0
  54. #endif
  55. #ifdef WINDOWS_NATIVE
  56. /* Optimized test whether a HANDLE refers to a console.
  57. See <http://lists.gnu.org/archive/html/bug-gnulib/2009-08/msg00065.html>. */
  58. #define IsConsoleHandle(h) (((intptr_t) (h) & 3) == 3)
  59. static BOOL
  60. IsSocketHandle (HANDLE h)
  61. {
  62. WSANETWORKEVENTS ev;
  63. if (IsConsoleHandle (h))
  64. return FALSE;
  65. /* Under Wine, it seems that getsockopt returns 0 for pipes too.
  66. WSAEnumNetworkEvents instead distinguishes the two correctly. */
  67. ev.lNetworkEvents = 0xDEADBEEF;
  68. WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
  69. return ev.lNetworkEvents != 0xDEADBEEF;
  70. }
  71. /* Declare data structures for ntdll functions. */
  72. typedef struct _FILE_PIPE_LOCAL_INFORMATION {
  73. ULONG NamedPipeType;
  74. ULONG NamedPipeConfiguration;
  75. ULONG MaximumInstances;
  76. ULONG CurrentInstances;
  77. ULONG InboundQuota;
  78. ULONG ReadDataAvailable;
  79. ULONG OutboundQuota;
  80. ULONG WriteQuotaAvailable;
  81. ULONG NamedPipeState;
  82. ULONG NamedPipeEnd;
  83. } FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION;
  84. typedef struct _IO_STATUS_BLOCK
  85. {
  86. union {
  87. DWORD Status;
  88. PVOID Pointer;
  89. } u;
  90. ULONG_PTR Information;
  91. } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
  92. typedef enum _FILE_INFORMATION_CLASS {
  93. FilePipeLocalInformation = 24
  94. } FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
  95. typedef DWORD (WINAPI *PNtQueryInformationFile)
  96. (HANDLE, IO_STATUS_BLOCK *, VOID *, ULONG, FILE_INFORMATION_CLASS);
  97. # ifndef PIPE_BUF
  98. # define PIPE_BUF 512
  99. # endif
  100. /* Compute revents values for file handle H. If some events cannot happen
  101. for the handle, eliminate them from *P_SOUGHT. */
  102. static int
  103. windows_compute_revents (HANDLE h, int *p_sought)
  104. {
  105. int i, ret, happened;
  106. INPUT_RECORD *irbuffer;
  107. DWORD avail, nbuffer;
  108. BOOL bRet;
  109. IO_STATUS_BLOCK iosb;
  110. FILE_PIPE_LOCAL_INFORMATION fpli;
  111. static PNtQueryInformationFile NtQueryInformationFile;
  112. static BOOL once_only;
  113. switch (GetFileType (h))
  114. {
  115. case FILE_TYPE_PIPE:
  116. if (!once_only)
  117. {
  118. NtQueryInformationFile = (PNtQueryInformationFile)
  119. GetProcAddress (GetModuleHandle ("ntdll.dll"),
  120. "NtQueryInformationFile");
  121. once_only = TRUE;
  122. }
  123. happened = 0;
  124. if (PeekNamedPipe (h, NULL, 0, NULL, &avail, NULL) != 0)
  125. {
  126. if (avail)
  127. happened |= *p_sought & (POLLIN | POLLRDNORM);
  128. }
  129. else if (GetLastError () == ERROR_BROKEN_PIPE)
  130. happened |= POLLHUP;
  131. else
  132. {
  133. /* It was the write-end of the pipe. Check if it is writable.
  134. If NtQueryInformationFile fails, optimistically assume the pipe is
  135. writable. This could happen on Windows 9x, where
  136. NtQueryInformationFile is not available, or if we inherit a pipe
  137. that doesn't permit FILE_READ_ATTRIBUTES access on the write end
  138. (I think this should not happen since Windows XP SP2; WINE seems
  139. fine too). Otherwise, ensure that enough space is available for
  140. atomic writes. */
  141. memset (&iosb, 0, sizeof (iosb));
  142. memset (&fpli, 0, sizeof (fpli));
  143. if (!NtQueryInformationFile
  144. || NtQueryInformationFile (h, &iosb, &fpli, sizeof (fpli),
  145. FilePipeLocalInformation)
  146. || fpli.WriteQuotaAvailable >= PIPE_BUF
  147. || (fpli.OutboundQuota < PIPE_BUF &&
  148. fpli.WriteQuotaAvailable == fpli.OutboundQuota))
  149. happened |= *p_sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
  150. }
  151. return happened;
  152. case FILE_TYPE_CHAR:
  153. ret = WaitForSingleObject (h, 0);
  154. if (!IsConsoleHandle (h))
  155. return ret == WAIT_OBJECT_0 ? *p_sought & ~(POLLPRI | POLLRDBAND) : 0;
  156. nbuffer = avail = 0;
  157. bRet = GetNumberOfConsoleInputEvents (h, &nbuffer);
  158. if (bRet)
  159. {
  160. /* Input buffer. */
  161. *p_sought &= POLLIN | POLLRDNORM;
  162. if (nbuffer == 0)
  163. return POLLHUP;
  164. if (!*p_sought)
  165. return 0;
  166. irbuffer = (INPUT_RECORD *) alloca (nbuffer * sizeof (INPUT_RECORD));
  167. bRet = PeekConsoleInput (h, irbuffer, nbuffer, &avail);
  168. if (!bRet || avail == 0)
  169. return POLLHUP;
  170. for (i = 0; i < avail; i++)
  171. if (irbuffer[i].EventType == KEY_EVENT)
  172. return *p_sought;
  173. return 0;
  174. }
  175. else
  176. {
  177. /* Screen buffer. */
  178. *p_sought &= POLLOUT | POLLWRNORM | POLLWRBAND;
  179. return *p_sought;
  180. }
  181. default:
  182. ret = WaitForSingleObject (h, 0);
  183. if (ret == WAIT_OBJECT_0)
  184. return *p_sought & ~(POLLPRI | POLLRDBAND);
  185. return *p_sought & (POLLOUT | POLLWRNORM | POLLWRBAND);
  186. }
  187. }
  188. /* Convert fd_sets returned by select into revents values. */
  189. static int
  190. windows_compute_revents_socket (SOCKET h, int sought, long lNetworkEvents)
  191. {
  192. int happened = 0;
  193. if ((lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) == FD_ACCEPT)
  194. happened |= (POLLIN | POLLRDNORM) & sought;
  195. else if (lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
  196. {
  197. int r, error;
  198. char data[64];
  199. WSASetLastError (0);
  200. r = recv (h, data, sizeof (data), MSG_PEEK);
  201. error = WSAGetLastError ();
  202. WSASetLastError (0);
  203. if (r > 0 || error == WSAENOTCONN)
  204. happened |= (POLLIN | POLLRDNORM) & sought;
  205. /* Distinguish hung-up sockets from other errors. */
  206. else if (r == 0 || error == WSAESHUTDOWN || error == WSAECONNRESET
  207. || error == WSAECONNABORTED || error == WSAENETRESET)
  208. happened |= POLLHUP;
  209. else
  210. happened |= POLLERR;
  211. }
  212. if (lNetworkEvents & (FD_WRITE | FD_CONNECT))
  213. happened |= (POLLOUT | POLLWRNORM | POLLWRBAND) & sought;
  214. if (lNetworkEvents & FD_OOB)
  215. happened |= (POLLPRI | POLLRDBAND) & sought;
  216. return happened;
  217. }
  218. #else /* !MinGW */
  219. /* Convert select(2) returned fd_sets into poll(2) revents values. */
  220. static int
  221. compute_revents (int fd, int sought, fd_set *rfds, fd_set *wfds, fd_set *efds)
  222. {
  223. int happened = 0;
  224. if (FD_ISSET (fd, rfds))
  225. {
  226. int r;
  227. int socket_errno;
  228. # if defined __MACH__ && defined __APPLE__
  229. /* There is a bug in Mac OS X that causes it to ignore MSG_PEEK
  230. for some kinds of descriptors. Detect if this descriptor is a
  231. connected socket, a server socket, or something else using a
  232. 0-byte recv, and use ioctl(2) to detect POLLHUP. */
  233. r = recv (fd, NULL, 0, MSG_PEEK);
  234. socket_errno = (r < 0) ? errno : 0;
  235. if (r == 0 || socket_errno == ENOTSOCK)
  236. ioctl (fd, FIONREAD, &r);
  237. # else
  238. char data[64];
  239. r = recv (fd, data, sizeof (data), MSG_PEEK);
  240. socket_errno = (r < 0) ? errno : 0;
  241. # endif
  242. if (r == 0)
  243. happened |= POLLHUP;
  244. /* If the event happened on an unconnected server socket,
  245. that's fine. */
  246. else if (r > 0 || ( /* (r == -1) && */ socket_errno == ENOTCONN))
  247. happened |= (POLLIN | POLLRDNORM) & sought;
  248. /* Distinguish hung-up sockets from other errors. */
  249. else if (socket_errno == ESHUTDOWN || socket_errno == ECONNRESET
  250. || socket_errno == ECONNABORTED || socket_errno == ENETRESET)
  251. happened |= POLLHUP;
  252. else
  253. happened |= POLLERR;
  254. }
  255. if (FD_ISSET (fd, wfds))
  256. happened |= (POLLOUT | POLLWRNORM | POLLWRBAND) & sought;
  257. if (FD_ISSET (fd, efds))
  258. happened |= (POLLPRI | POLLRDBAND) & sought;
  259. return happened;
  260. }
  261. #endif /* !MinGW */
  262. int
  263. poll (struct pollfd *pfd, nfds_t nfd, int timeout)
  264. {
  265. #ifndef WINDOWS_NATIVE
  266. fd_set rfds, wfds, efds;
  267. struct timeval tv;
  268. struct timeval *ptv;
  269. int maxfd, rc;
  270. nfds_t i;
  271. # ifdef _SC_OPEN_MAX
  272. static int sc_open_max = -1;
  273. if (nfd < 0
  274. || (nfd > sc_open_max
  275. && (sc_open_max != -1
  276. || nfd > (sc_open_max = sysconf (_SC_OPEN_MAX)))))
  277. {
  278. errno = EINVAL;
  279. return -1;
  280. }
  281. # else /* !_SC_OPEN_MAX */
  282. # ifdef OPEN_MAX
  283. if (nfd < 0 || nfd > OPEN_MAX)
  284. {
  285. errno = EINVAL;
  286. return -1;
  287. }
  288. # endif /* OPEN_MAX -- else, no check is needed */
  289. # endif /* !_SC_OPEN_MAX */
  290. /* EFAULT is not necessary to implement, but let's do it in the
  291. simplest case. */
  292. if (!pfd)
  293. {
  294. errno = EFAULT;
  295. return -1;
  296. }
  297. /* convert timeout number into a timeval structure */
  298. if (timeout == 0)
  299. {
  300. ptv = &tv;
  301. ptv->tv_sec = 0;
  302. ptv->tv_usec = 0;
  303. }
  304. else if (timeout > 0)
  305. {
  306. ptv = &tv;
  307. ptv->tv_sec = timeout / 1000;
  308. ptv->tv_usec = (timeout % 1000) * 1000;
  309. }
  310. else if (timeout == INFTIM)
  311. /* wait forever */
  312. ptv = NULL;
  313. else
  314. {
  315. errno = EINVAL;
  316. return -1;
  317. }
  318. /* create fd sets and determine max fd */
  319. maxfd = -1;
  320. FD_ZERO (&rfds);
  321. FD_ZERO (&wfds);
  322. FD_ZERO (&efds);
  323. for (i = 0; i < nfd; i++)
  324. {
  325. if (pfd[i].fd < 0)
  326. continue;
  327. if (pfd[i].events & (POLLIN | POLLRDNORM))
  328. FD_SET (pfd[i].fd, &rfds);
  329. /* see select(2): "the only exceptional condition detectable
  330. is out-of-band data received on a socket", hence we push
  331. POLLWRBAND events onto wfds instead of efds. */
  332. if (pfd[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND))
  333. FD_SET (pfd[i].fd, &wfds);
  334. if (pfd[i].events & (POLLPRI | POLLRDBAND))
  335. FD_SET (pfd[i].fd, &efds);
  336. if (pfd[i].fd >= maxfd
  337. && (pfd[i].events & (POLLIN | POLLOUT | POLLPRI
  338. | POLLRDNORM | POLLRDBAND
  339. | POLLWRNORM | POLLWRBAND)))
  340. {
  341. maxfd = pfd[i].fd;
  342. if (maxfd > FD_SETSIZE)
  343. {
  344. errno = EOVERFLOW;
  345. return -1;
  346. }
  347. }
  348. }
  349. /* examine fd sets */
  350. rc = select (maxfd + 1, &rfds, &wfds, &efds, ptv);
  351. if (rc < 0)
  352. return rc;
  353. /* establish results */
  354. rc = 0;
  355. for (i = 0; i < nfd; i++)
  356. if (pfd[i].fd < 0)
  357. pfd[i].revents = 0;
  358. else
  359. {
  360. int happened = compute_revents (pfd[i].fd, pfd[i].events,
  361. &rfds, &wfds, &efds);
  362. if (happened)
  363. {
  364. pfd[i].revents = happened;
  365. rc++;
  366. }
  367. }
  368. return rc;
  369. #else
  370. static struct timeval tv0;
  371. static HANDLE hEvent;
  372. WSANETWORKEVENTS ev;
  373. HANDLE h, handle_array[FD_SETSIZE + 2];
  374. DWORD ret, wait_timeout, nhandles;
  375. fd_set rfds, wfds, xfds;
  376. BOOL poll_again;
  377. MSG msg;
  378. int rc = 0;
  379. nfds_t i;
  380. if (nfd < 0 || timeout < -1)
  381. {
  382. errno = EINVAL;
  383. return -1;
  384. }
  385. if (!hEvent)
  386. hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
  387. restart:
  388. handle_array[0] = hEvent;
  389. nhandles = 1;
  390. FD_ZERO (&rfds);
  391. FD_ZERO (&wfds);
  392. FD_ZERO (&xfds);
  393. /* Classify socket handles and create fd sets. */
  394. for (i = 0; i < nfd; i++)
  395. {
  396. int sought = pfd[i].events;
  397. pfd[i].revents = 0;
  398. if (pfd[i].fd < 0)
  399. continue;
  400. if (!(sought & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM | POLLWRBAND
  401. | POLLPRI | POLLRDBAND)))
  402. continue;
  403. h = (HANDLE) _get_osfhandle (pfd[i].fd);
  404. assert (h != NULL);
  405. if (IsSocketHandle (h))
  406. {
  407. int requested = FD_CLOSE;
  408. /* see above; socket handles are mapped onto select. */
  409. if (sought & (POLLIN | POLLRDNORM))
  410. {
  411. requested |= FD_READ | FD_ACCEPT;
  412. FD_SET ((SOCKET) h, &rfds);
  413. }
  414. if (sought & (POLLOUT | POLLWRNORM | POLLWRBAND))
  415. {
  416. requested |= FD_WRITE | FD_CONNECT;
  417. FD_SET ((SOCKET) h, &wfds);
  418. }
  419. if (sought & (POLLPRI | POLLRDBAND))
  420. {
  421. requested |= FD_OOB;
  422. FD_SET ((SOCKET) h, &xfds);
  423. }
  424. if (requested)
  425. WSAEventSelect ((SOCKET) h, hEvent, requested);
  426. }
  427. else
  428. {
  429. /* Poll now. If we get an event, do not poll again. Also,
  430. screen buffer handles are waitable, and they'll block until
  431. a character is available. windows_compute_revents eliminates
  432. bits for the "wrong" direction. */
  433. pfd[i].revents = windows_compute_revents (h, &sought);
  434. if (sought)
  435. handle_array[nhandles++] = h;
  436. if (pfd[i].revents)
  437. timeout = 0;
  438. }
  439. }
  440. if (select (0, &rfds, &wfds, &xfds, &tv0) > 0)
  441. {
  442. /* Do MsgWaitForMultipleObjects anyway to dispatch messages, but
  443. no need to call select again. */
  444. poll_again = FALSE;
  445. wait_timeout = 0;
  446. }
  447. else
  448. {
  449. poll_again = TRUE;
  450. if (timeout == INFTIM)
  451. wait_timeout = INFINITE;
  452. else
  453. wait_timeout = timeout;
  454. }
  455. for (;;)
  456. {
  457. ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
  458. wait_timeout, QS_ALLINPUT);
  459. if (ret == WAIT_OBJECT_0 + nhandles)
  460. {
  461. /* new input of some other kind */
  462. BOOL bRet;
  463. while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
  464. {
  465. TranslateMessage (&msg);
  466. DispatchMessage (&msg);
  467. }
  468. }
  469. else
  470. break;
  471. }
  472. if (poll_again)
  473. select (0, &rfds, &wfds, &xfds, &tv0);
  474. /* Place a sentinel at the end of the array. */
  475. handle_array[nhandles] = NULL;
  476. nhandles = 1;
  477. for (i = 0; i < nfd; i++)
  478. {
  479. int happened;
  480. if (pfd[i].fd < 0)
  481. continue;
  482. if (!(pfd[i].events & (POLLIN | POLLRDNORM |
  483. POLLOUT | POLLWRNORM | POLLWRBAND)))
  484. continue;
  485. h = (HANDLE) _get_osfhandle (pfd[i].fd);
  486. if (h != handle_array[nhandles])
  487. {
  488. /* It's a socket. */
  489. WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
  490. WSAEventSelect ((SOCKET) h, 0, 0);
  491. /* If we're lucky, WSAEnumNetworkEvents already provided a way
  492. to distinguish FD_READ and FD_ACCEPT; this saves a recv later. */
  493. if (FD_ISSET ((SOCKET) h, &rfds)
  494. && !(ev.lNetworkEvents & (FD_READ | FD_ACCEPT)))
  495. ev.lNetworkEvents |= FD_READ | FD_ACCEPT;
  496. if (FD_ISSET ((SOCKET) h, &wfds))
  497. ev.lNetworkEvents |= FD_WRITE | FD_CONNECT;
  498. if (FD_ISSET ((SOCKET) h, &xfds))
  499. ev.lNetworkEvents |= FD_OOB;
  500. happened = windows_compute_revents_socket ((SOCKET) h, pfd[i].events,
  501. ev.lNetworkEvents);
  502. }
  503. else
  504. {
  505. /* Not a socket. */
  506. int sought = pfd[i].events;
  507. happened = windows_compute_revents (h, &sought);
  508. nhandles++;
  509. }
  510. if ((pfd[i].revents |= happened) != 0)
  511. rc++;
  512. }
  513. if (!rc && timeout == INFTIM)
  514. {
  515. SleepEx (1, TRUE);
  516. goto restart;
  517. }
  518. return rc;
  519. #endif
  520. }