Use POSIX-specified <poll.h> over <sys/poll.h>
[platform/upstream/glib.git] / glib / gpoll.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gpoll.c: poll(2) abstraction
5  * Copyright 1998 Owen Taylor
6  * Copyright 2008 Red Hat, Inc.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /*
25  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
26  * file for a list of people on the GLib Team.  See the ChangeLog
27  * files for a list of changes.  These files are distributed with
28  * GLib at ftp://ftp.gtk.org/pub/gtk/.
29  */
30
31 /*
32  * MT safe
33  */
34
35 #include "config.h"
36 #include "glibconfig.h"
37 #include "giochannel.h"
38
39 /* Uncomment the next line (and the corresponding line in gmain.c) to
40  * enable debugging printouts if the environment variable
41  * G_MAIN_POLL_DEBUG is set to some value.
42  */
43 /* #define G_MAIN_POLL_DEBUG */
44
45 #ifdef _WIN32
46 /* Always enable debugging printout on Windows, as it is more often
47  * needed there...
48  */
49 #define G_MAIN_POLL_DEBUG
50 #endif
51
52 #include <sys/types.h>
53 #include <time.h>
54 #include <stdlib.h>
55 #ifdef HAVE_SYS_TIME_H
56 #include <sys/time.h>
57 #endif /* HAVE_SYS_TIME_H */
58 #ifdef HAVE_POLL
59 #  include <poll.h>
60
61 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
62  * so we prefer our own poll emulation.
63  */
64 #if defined(_POLL_EMUL_H_) || defined(BROKEN_POLL)
65 #undef HAVE_POLL
66 #endif
67
68 #endif /* GLIB_HAVE_SYS_POLL_H */
69 #ifdef G_OS_UNIX
70 #include <unistd.h>
71 #endif /* G_OS_UNIX */
72 #include <errno.h>
73
74 #ifdef G_OS_WIN32
75 #define STRICT
76 #include <windows.h>
77 #endif /* G_OS_WIN32 */
78
79 #include "gpoll.h"
80
81 #ifdef G_OS_WIN32
82 #include "gprintf.h"
83 #endif
84
85 #ifdef G_MAIN_POLL_DEBUG
86 extern gboolean _g_main_poll_debug;
87 #endif
88
89 #ifdef HAVE_POLL
90
91 /**
92  * g_poll:
93  * @fds: file descriptors to poll
94  * @nfds: the number of file descriptors in @fds
95  * @timeout: amount of time to wait, in milliseconds, or -1 to wait forever
96  *
97  * Polls @fds, as with the poll() system call, but portably. (On
98  * systems that don't have poll(), it is emulated using select().)
99  * This is used internally by #GMainContext, but it can be called
100  * directly if you need to block until a file descriptor is ready, but
101  * don't want to run the full main loop.
102  *
103  * Each element of @fds is a #GPollFD describing a single file
104  * descriptor to poll. The %fd field indicates the file descriptor,
105  * and the %events field indicates the events to poll for. On return,
106  * the %revents fields will be filled with the events that actually
107  * occurred.
108  *
109  * On POSIX systems, the file descriptors in @fds can be any sort of
110  * file descriptor, but the situation is much more complicated on
111  * Windows. If you need to use g_poll() in code that has to run on
112  * Windows, the easiest solution is to construct all of your
113  * #GPollFD<!-- -->s with g_io_channel_win32_make_pollfd().
114  *
115  * Return value: the number of entries in @fds whose %revents fields
116  * were filled in, or 0 if the operation timed out, or -1 on error or
117  * if the call was interrupted.
118  *
119  * Since: 2.20
120  **/
121 gint
122 g_poll (GPollFD *fds,
123         guint    nfds,
124         gint     timeout)
125 {
126   return poll ((struct pollfd *)fds, nfds, timeout);
127 }
128
129 #else   /* !HAVE_POLL */
130
131 #ifdef G_OS_WIN32
132
133 static int
134 poll_rest (gboolean  poll_msgs,
135            HANDLE   *handles,
136            gint      nhandles,
137            GPollFD  *fds,
138            guint     nfds,
139            gint      timeout)
140 {
141   DWORD ready;
142   GPollFD *f;
143   int recursed_result;
144
145   if (poll_msgs)
146     {
147       /* Wait for either messages or handles
148        * -> Use MsgWaitForMultipleObjectsEx
149        */
150       if (_g_main_poll_debug)
151         g_print ("  MsgWaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
152
153       ready = MsgWaitForMultipleObjectsEx (nhandles, handles, timeout,
154                                            QS_ALLINPUT, MWMO_ALERTABLE);
155
156       if (ready == WAIT_FAILED)
157         {
158           gchar *emsg = g_win32_error_message (GetLastError ());
159           g_warning ("MsgWaitForMultipleObjectsEx failed: %s", emsg);
160           g_free (emsg);
161         }
162     }
163   else if (nhandles == 0)
164     {
165       /* No handles to wait for, just the timeout */
166       if (timeout == INFINITE)
167         ready = WAIT_FAILED;
168       else
169         {
170           SleepEx (timeout, TRUE);
171           ready = WAIT_TIMEOUT;
172         }
173     }
174   else
175     {
176       /* Wait for just handles
177        * -> Use WaitForMultipleObjectsEx
178        */
179       if (_g_main_poll_debug)
180         g_print ("  WaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
181
182       ready = WaitForMultipleObjectsEx (nhandles, handles, FALSE, timeout, TRUE);
183       if (ready == WAIT_FAILED)
184         {
185           gchar *emsg = g_win32_error_message (GetLastError ());
186           g_warning ("WaitForMultipleObjectsEx failed: %s", emsg);
187           g_free (emsg);
188         }
189     }
190
191   if (_g_main_poll_debug)
192     g_print ("  wait returns %ld%s\n",
193              ready,
194              (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
195               (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
196                (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
197
198   if (ready == WAIT_FAILED)
199     return -1;
200   else if (ready == WAIT_TIMEOUT ||
201            ready == WAIT_IO_COMPLETION)
202     return 0;
203   else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
204     {
205       for (f = fds; f < &fds[nfds]; ++f)
206         if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN)
207           f->revents |= G_IO_IN;
208
209       /* If we have a timeout, or no handles to poll, be satisfied
210        * with just noticing we have messages waiting.
211        */
212       if (timeout != 0 || nhandles == 0)
213         return 1;
214
215       /* If no timeout and handles to poll, recurse to poll them,
216        * too.
217        */
218       recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
219       return (recursed_result == -1) ? -1 : 1 + recursed_result;
220     }
221   else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
222     {
223       for (f = fds; f < &fds[nfds]; ++f)
224         {
225           if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0])
226             {
227               f->revents = f->events;
228               if (_g_main_poll_debug)
229                 g_print ("  got event %p\n", (HANDLE) f->fd);
230             }
231         }
232
233       /* If no timeout and polling several handles, recurse to poll
234        * the rest of them.
235        */
236       if (timeout == 0 && nhandles > 1)
237         {
238           /* Remove the handle that fired */
239           int i;
240           if (ready < nhandles - 1)
241             for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++)
242               handles[i-1] = handles[i];
243           nhandles--;
244           recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
245           return (recursed_result == -1) ? -1 : 1 + recursed_result;
246         }
247       return 1;
248     }
249
250   return 0;
251 }
252
253 gint
254 g_poll (GPollFD *fds,
255         guint    nfds,
256         gint     timeout)
257 {
258   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
259   gboolean poll_msgs = FALSE;
260   GPollFD *f;
261   gint nhandles = 0;
262   int retval;
263
264   if (_g_main_poll_debug)
265     g_print ("g_poll: waiting for");
266
267   for (f = fds; f < &fds[nfds]; ++f)
268     if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN))
269       {
270         if (_g_main_poll_debug && !poll_msgs)
271           g_print (" MSG");
272         poll_msgs = TRUE;
273       }
274     else if (f->fd > 0)
275       {
276         /* Don't add the same handle several times into the array, as
277          * docs say that is not allowed, even if it actually does seem
278          * to work.
279          */
280         gint i;
281
282         for (i = 0; i < nhandles; i++)
283           if (handles[i] == (HANDLE) f->fd)
284             break;
285
286         if (i == nhandles)
287           {
288             if (nhandles == MAXIMUM_WAIT_OBJECTS)
289               {
290                 g_warning ("Too many handles to wait for!\n");
291                 break;
292               }
293             else
294               {
295                 if (_g_main_poll_debug)
296                   g_print (" %p", (HANDLE) f->fd);
297                 handles[nhandles++] = (HANDLE) f->fd;
298               }
299           }
300       }
301
302   if (_g_main_poll_debug)
303     g_print ("\n");
304
305   for (f = fds; f < &fds[nfds]; ++f)
306     f->revents = 0;
307
308   if (timeout == -1)
309     timeout = INFINITE;
310
311   /* Polling for several things? */
312   if (nhandles > 1 || (nhandles > 0 && poll_msgs))
313     {
314       /* First check if one or several of them are immediately
315        * available
316        */
317       retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, 0);
318
319       /* If not, and we have a significant timeout, poll again with
320        * timeout then. Note that this will return indication for only
321        * one event, or only for messages. We ignore timeouts less than
322        * ten milliseconds as they are mostly pointless on Windows, the
323        * MsgWaitForMultipleObjectsEx() call will timeout right away
324        * anyway.
325        */
326       if (retval == 0 && (timeout == INFINITE || timeout >= 10))
327         retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
328     }
329   else
330     {
331       /* Just polling for one thing, so no need to check first if
332        * available immediately
333        */
334       retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
335     }
336
337   if (retval == -1)
338     for (f = fds; f < &fds[nfds]; ++f)
339       f->revents = 0;
340
341   return retval;
342 }
343
344 #else  /* !G_OS_WIN32 */
345
346 /* The following implementation of poll() comes from the GNU C Library.
347  * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
348  */
349
350 #include <string.h> /* for bzero on BSD systems */
351
352 #ifdef HAVE_SYS_SELECT_H
353 #include <sys/select.h>
354 #endif /* HAVE_SYS_SELECT_H */
355
356 #ifndef NO_FD_SET
357 #  define SELECT_MASK fd_set
358 #else /* !NO_FD_SET */
359 #  ifndef _AIX
360 typedef long fd_mask;
361 #  endif /* _AIX */
362 #  ifdef _IBMR2
363 #    define SELECT_MASK void
364 #  else /* !_IBMR2 */
365 #    define SELECT_MASK int
366 #  endif /* !_IBMR2 */
367 #endif /* !NO_FD_SET */
368
369 gint
370 g_poll (GPollFD *fds,
371         guint    nfds,
372         gint     timeout)
373 {
374   struct timeval tv;
375   SELECT_MASK rset, wset, xset;
376   GPollFD *f;
377   int ready;
378   int maxfd = 0;
379
380   FD_ZERO (&rset);
381   FD_ZERO (&wset);
382   FD_ZERO (&xset);
383
384   for (f = fds; f < &fds[nfds]; ++f)
385     if (f->fd >= 0)
386       {
387         if (f->events & G_IO_IN)
388           FD_SET (f->fd, &rset);
389         if (f->events & G_IO_OUT)
390           FD_SET (f->fd, &wset);
391         if (f->events & G_IO_PRI)
392           FD_SET (f->fd, &xset);
393         if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
394           maxfd = f->fd;
395       }
396
397   tv.tv_sec = timeout / 1000;
398   tv.tv_usec = (timeout % 1000) * 1000;
399
400   ready = select (maxfd + 1, &rset, &wset, &xset,
401                   timeout == -1 ? NULL : &tv);
402   if (ready > 0)
403     for (f = fds; f < &fds[nfds]; ++f)
404       {
405         f->revents = 0;
406         if (f->fd >= 0)
407           {
408             if (FD_ISSET (f->fd, &rset))
409               f->revents |= G_IO_IN;
410             if (FD_ISSET (f->fd, &wset))
411               f->revents |= G_IO_OUT;
412             if (FD_ISSET (f->fd, &xset))
413               f->revents |= G_IO_PRI;
414           }
415       }
416
417   return ready;
418 }
419
420 #endif /* !G_OS_WIN32 */
421
422 #endif  /* !HAVE_POLL */