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