PageRenderTime 48ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/compat/poll/poll.c

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