Merge remote-tracking branch 'gvdb/master'
[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 GLIB_HAVE_SYS_POLL_H
59 #  include <sys/poll.h>
60 #  undef events  /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
61 #  undef revents /* AIX 4.1.5 & 4.3.2 define this for SVR3,4 compatibility */
62
63 /* The poll() emulation on OS/X doesn't handle fds=NULL, nfds=0,
64  * so we prefer our own poll emulation.
65  */
66 #if defined(_POLL_EMUL_H_) || defined(BROKEN_POLL)
67 #undef HAVE_POLL
68 #endif
69
70 #endif /* GLIB_HAVE_SYS_POLL_H */
71 #ifdef HAVE_UNISTD_H
72 #include <unistd.h>
73 #endif /* HAVE_UNISTD_H */
74 #include <errno.h>
75
76 #ifdef G_OS_WIN32
77 #define STRICT
78 #include <windows.h>
79 #endif /* G_OS_WIN32 */
80
81 #include "gpoll.h"
82
83 #ifdef G_OS_WIN32
84 #include "gprintf.h"
85 #endif
86
87 #ifdef G_MAIN_POLL_DEBUG
88 extern gboolean _g_main_poll_debug;
89 #endif
90
91 #ifdef HAVE_POLL
92 /* SunOS has poll, but doesn't provide a prototype. */
93 #  if defined (sun) && !defined (__SVR4)
94 extern gint poll (struct pollfd *fds, guint nfsd, gint timeout);
95 #  endif  /* !sun */
96
97 /**
98  * g_poll:
99  * @fds: file descriptors to poll
100  * @nfds: the number of file descriptors in @fds
101  * @timeout: amount of time to wait, in milliseconds, or -1 to wait forever
102  *
103  * Polls @fds, as with the poll() system call, but portably. (On
104  * systems that don't have poll(), it is emulated using select().)
105  * This is used internally by #GMainContext, but it can be called
106  * directly if you need to block until a file descriptor is ready, but
107  * don't want to run the full main loop.
108  *
109  * Each element of @fds is a #GPollFD describing a single file
110  * descriptor to poll. The %fd field indicates the file descriptor,
111  * and the %events field indicates the events to poll for. On return,
112  * the %revents fields will be filled with the events that actually
113  * occurred.
114  *
115  * On POSIX systems, the file descriptors in @fds can be any sort of
116  * file descriptor, but the situation is much more complicated on
117  * Windows. If you need to use g_poll() in code that has to run on
118  * Windows, the easiest solution is to construct all of your
119  * #GPollFD<!-- -->s with g_io_channel_win32_make_pollfd().
120  *
121  * Return value: the number of entries in @fds whose %revents fields
122  * were filled in, or 0 if the operation timed out, or -1 on error or
123  * if the call was interrupted.
124  *
125  * Since: 2.20
126  **/
127 gint
128 g_poll (GPollFD *fds,
129         guint    nfds,
130         gint     timeout)
131 {
132   return poll ((struct pollfd *)fds, nfds, timeout);
133 }
134
135 #else   /* !HAVE_POLL */
136
137 #ifdef G_OS_WIN32
138
139 static int
140 poll_rest (gboolean  poll_msgs,
141            HANDLE   *handles,
142            gint      nhandles,
143            GPollFD  *fds,
144            guint     nfds,
145            gint      timeout)
146 {
147   DWORD ready;
148   GPollFD *f;
149   int recursed_result;
150
151   if (poll_msgs)
152     {
153       /* Wait for either messages or handles
154        * -> Use MsgWaitForMultipleObjectsEx
155        */
156       if (_g_main_poll_debug)
157         g_print ("  MsgWaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
158
159       ready = MsgWaitForMultipleObjectsEx (nhandles, handles, timeout,
160                                            QS_ALLINPUT, MWMO_ALERTABLE);
161
162       if (ready == WAIT_FAILED)
163         {
164           gchar *emsg = g_win32_error_message (GetLastError ());
165           g_warning ("MsgWaitForMultipleObjectsEx failed: %s", emsg);
166           g_free (emsg);
167         }
168     }
169   else if (nhandles == 0)
170     {
171       /* No handles to wait for, just the timeout */
172       if (timeout == INFINITE)
173         ready = WAIT_FAILED;
174       else
175         {
176           SleepEx (timeout, TRUE);
177           ready = WAIT_TIMEOUT;
178         }
179     }
180   else
181     {
182       /* Wait for just handles
183        * -> Use WaitForMultipleObjectsEx
184        */
185       if (_g_main_poll_debug)
186         g_print ("  WaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
187
188       ready = WaitForMultipleObjectsEx (nhandles, handles, FALSE, timeout, TRUE);
189       if (ready == WAIT_FAILED)
190         {
191           gchar *emsg = g_win32_error_message (GetLastError ());
192           g_warning ("WaitForMultipleObjectsEx failed: %s", emsg);
193           g_free (emsg);
194         }
195     }
196
197   if (_g_main_poll_debug)
198     g_print ("  wait returns %ld%s\n",
199              ready,
200              (ready == WAIT_FAILED ? " (WAIT_FAILED)" :
201               (ready == WAIT_TIMEOUT ? " (WAIT_TIMEOUT)" :
202                (poll_msgs && ready == WAIT_OBJECT_0 + nhandles ? " (msg)" : ""))));
203
204   if (ready == WAIT_FAILED)
205     return -1;
206   else if (ready == WAIT_TIMEOUT ||
207            ready == WAIT_IO_COMPLETION)
208     return 0;
209   else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles)
210     {
211       for (f = fds; f < &fds[nfds]; ++f)
212         if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN)
213           f->revents |= G_IO_IN;
214
215       /* If we have a timeout, or no handles to poll, be satisfied
216        * with just noticing we have messages waiting.
217        */
218       if (timeout != 0 || nhandles == 0)
219         return 1;
220
221       /* If no timeout and handles to poll, recurse to poll them,
222        * too.
223        */
224       recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
225       return (recursed_result == -1) ? -1 : 1 + recursed_result;
226     }
227   else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
228     {
229       for (f = fds; f < &fds[nfds]; ++f)
230         {
231           if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0])
232             {
233               f->revents = f->events;
234               if (_g_main_poll_debug)
235                 g_print ("  got event %p\n", (HANDLE) f->fd);
236             }
237         }
238
239       /* If no timeout and polling several handles, recurse to poll
240        * the rest of them.
241        */
242       if (timeout == 0 && nhandles > 1)
243         {
244           /* Remove the handle that fired */
245           int i;
246           if (ready < nhandles - 1)
247             for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++)
248               handles[i-1] = handles[i];
249           nhandles--;
250           recursed_result = poll_rest (FALSE, handles, nhandles, fds, nfds, 0);
251           return (recursed_result == -1) ? -1 : 1 + recursed_result;
252         }
253       return 1;
254     }
255
256   return 0;
257 }
258
259 gint
260 g_poll (GPollFD *fds,
261         guint    nfds,
262         gint     timeout)
263 {
264   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
265   gboolean poll_msgs = FALSE;
266   GPollFD *f;
267   gint nhandles = 0;
268   int retval;
269
270   if (_g_main_poll_debug)
271     g_print ("g_poll: waiting for");
272
273   for (f = fds; f < &fds[nfds]; ++f)
274     if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN))
275       {
276         if (_g_main_poll_debug && !poll_msgs)
277           g_print (" MSG");
278         poll_msgs = TRUE;
279       }
280     else if (f->fd > 0)
281       {
282         /* Don't add the same handle several times into the array, as
283          * docs say that is not allowed, even if it actually does seem
284          * to work.
285          */
286         gint i;
287
288         for (i = 0; i < nhandles; i++)
289           if (handles[i] == (HANDLE) f->fd)
290             break;
291
292         if (i == nhandles)
293           {
294             if (nhandles == MAXIMUM_WAIT_OBJECTS)
295               {
296                 g_warning ("Too many handles to wait for!\n");
297                 break;
298               }
299             else
300               {
301                 if (_g_main_poll_debug)
302                   g_print (" %p", (HANDLE) f->fd);
303                 handles[nhandles++] = (HANDLE) f->fd;
304               }
305           }
306       }
307
308   if (_g_main_poll_debug)
309     g_print ("\n");
310
311   for (f = fds; f < &fds[nfds]; ++f)
312     f->revents = 0;
313
314   if (timeout == -1)
315     timeout = INFINITE;
316
317   /* Polling for several things? */
318   if (nhandles > 1 || (nhandles > 0 && poll_msgs))
319     {
320       /* First check if one or several of them are immediately
321        * available
322        */
323       retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, 0);
324
325       /* If not, and we have a significant timeout, poll again with
326        * timeout then. Note that this will return indication for only
327        * one event, or only for messages. We ignore timeouts less than
328        * ten milliseconds as they are mostly pointless on Windows, the
329        * MsgWaitForMultipleObjectsEx() call will timeout right away
330        * anyway.
331        */
332       if (retval == 0 && (timeout == INFINITE || timeout >= 10))
333         retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
334     }
335   else
336     {
337       /* Just polling for one thing, so no need to check first if
338        * available immediately
339        */
340       retval = poll_rest (poll_msgs, handles, nhandles, fds, nfds, timeout);
341     }
342
343   if (retval == -1)
344     for (f = fds; f < &fds[nfds]; ++f)
345       f->revents = 0;
346
347   return retval;
348 }
349
350 #else  /* !G_OS_WIN32 */
351
352 /* The following implementation of poll() comes from the GNU C Library.
353  * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
354  */
355
356 #include <string.h> /* for bzero on BSD systems */
357
358 #ifdef HAVE_SYS_SELECT_H
359 #include <sys/select.h>
360 #endif /* HAVE_SYS_SELECT_H */
361
362 #ifdef G_OS_BEOS
363 #undef NO_FD_SET
364 #endif /* G_OS_BEOS */
365
366 #ifndef NO_FD_SET
367 #  define SELECT_MASK fd_set
368 #else /* !NO_FD_SET */
369 #  ifndef _AIX
370 typedef long fd_mask;
371 #  endif /* _AIX */
372 #  ifdef _IBMR2
373 #    define SELECT_MASK void
374 #  else /* !_IBMR2 */
375 #    define SELECT_MASK int
376 #  endif /* !_IBMR2 */
377 #endif /* !NO_FD_SET */
378
379 gint
380 g_poll (GPollFD *fds,
381         guint    nfds,
382         gint     timeout)
383 {
384   struct timeval tv;
385   SELECT_MASK rset, wset, xset;
386   GPollFD *f;
387   int ready;
388   int maxfd = 0;
389
390   FD_ZERO (&rset);
391   FD_ZERO (&wset);
392   FD_ZERO (&xset);
393
394   for (f = fds; f < &fds[nfds]; ++f)
395     if (f->fd >= 0)
396       {
397         if (f->events & G_IO_IN)
398           FD_SET (f->fd, &rset);
399         if (f->events & G_IO_OUT)
400           FD_SET (f->fd, &wset);
401         if (f->events & G_IO_PRI)
402           FD_SET (f->fd, &xset);
403         if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
404           maxfd = f->fd;
405       }
406
407   tv.tv_sec = timeout / 1000;
408   tv.tv_usec = (timeout % 1000) * 1000;
409
410   ready = select (maxfd + 1, &rset, &wset, &xset,
411                   timeout == -1 ? NULL : &tv);
412   if (ready > 0)
413     for (f = fds; f < &fds[nfds]; ++f)
414       {
415         f->revents = 0;
416         if (f->fd >= 0)
417           {
418             if (FD_ISSET (f->fd, &rset))
419               f->revents |= G_IO_IN;
420             if (FD_ISSET (f->fd, &wset))
421               f->revents |= G_IO_OUT;
422             if (FD_ISSET (f->fd, &xset))
423               f->revents |= G_IO_PRI;
424           }
425       }
426
427   return ready;
428 }
429
430 #endif /* !G_OS_WIN32 */
431
432 #endif  /* !HAVE_POLL */