Imported Upstream version 2.57.1
[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.1 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 (GPollFD *msg_fd,
133            HANDLE  *handles,
134            GPollFD *handle_to_fd[],
135            gint     nhandles,
136            gint     timeout)
137 {
138   DWORD ready;
139   GPollFD *f;
140   int recursed_result;
141
142   if (msg_fd != NULL)
143     {
144       /* Wait for either messages or handles
145        * -> Use MsgWaitForMultipleObjectsEx
146        */
147       if (_g_main_poll_debug)
148         g_print ("  MsgWaitForMultipleObjectsEx(%d, %d)\n", nhandles, timeout);
149
150       ready = MsgWaitForMultipleObjectsEx (nhandles, handles, timeout,
151                                            QS_ALLINPUT, MWMO_ALERTABLE);
152
153       if (ready == WAIT_FAILED)
154         {
155           gchar *emsg = g_win32_error_message (GetLastError ());
156           g_warning ("MsgWaitForMultipleObjectsEx failed: %s", emsg);
157           g_free (emsg);
158         }
159     }
160   else if (nhandles == 0)
161     {
162       /* No handles to wait for, just the timeout */
163       if (timeout == INFINITE)
164         ready = WAIT_FAILED;
165       else
166         {
167           /* Wait for the current process to die, more efficient than SleepEx(). */
168           WaitForSingleObjectEx (GetCurrentProcess (), 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                (msg_fd != NULL && 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 (msg_fd != NULL && ready == WAIT_OBJECT_0 + nhandles)
202     {
203       msg_fd->revents |= G_IO_IN;
204
205       /* If we have a timeout, or no handles to poll, be satisfied
206        * with just noticing we have messages waiting.
207        */
208       if (timeout != 0 || nhandles == 0)
209         return 1;
210
211       /* If no timeout and handles to poll, recurse to poll them,
212        * too.
213        */
214       recursed_result = poll_rest (NULL, handles, handle_to_fd, nhandles, 0);
215       return (recursed_result == -1) ? -1 : 1 + recursed_result;
216     }
217   else if (ready >= WAIT_OBJECT_0 && ready < WAIT_OBJECT_0 + nhandles)
218     {
219       f = handle_to_fd[ready - WAIT_OBJECT_0];
220       f->revents = f->events;
221       if (_g_main_poll_debug)
222         g_print ("  got event %p\n", (HANDLE) f->fd);
223
224       /* If no timeout and polling several handles, recurse to poll
225        * the rest of them.
226        */
227       if (timeout == 0 && nhandles > 1)
228         {
229           /* Poll the handles with index > ready */
230           HANDLE  *shorter_handles;
231           GPollFD **shorter_handle_to_fd;
232           gint     shorter_nhandles;
233
234           shorter_handles = &handles[ready - WAIT_OBJECT_0 + 1];
235           shorter_handle_to_fd = &handle_to_fd[ready - WAIT_OBJECT_0 + 1];
236           shorter_nhandles = nhandles - (ready - WAIT_OBJECT_0 + 1);
237
238           recursed_result = poll_rest (NULL, shorter_handles, shorter_handle_to_fd, shorter_nhandles, 0);
239           return (recursed_result == -1) ? -1 : 1 + recursed_result;
240         }
241       return 1;
242     }
243
244   return 0;
245 }
246
247 gint
248 g_poll (GPollFD *fds,
249         guint    nfds,
250         gint     timeout)
251 {
252   HANDLE handles[MAXIMUM_WAIT_OBJECTS];
253   GPollFD *handle_to_fd[MAXIMUM_WAIT_OBJECTS];
254   GPollFD *msg_fd = NULL;
255   GPollFD *f;
256   gint nhandles = 0;
257   int retval;
258
259   if (_g_main_poll_debug)
260     g_print ("g_poll: waiting for");
261
262   for (f = fds; f < &fds[nfds]; ++f)
263     {
264       if (f->fd == G_WIN32_MSG_HANDLE && (f->events & G_IO_IN))
265         {
266           if (_g_main_poll_debug && msg_fd == NULL)
267             g_print (" MSG");
268           msg_fd = f;
269         }
270       else if (f->fd > 0)
271         {
272           if (nhandles == MAXIMUM_WAIT_OBJECTS)
273             {
274               g_warning ("Too many handles to wait for!");
275               break;
276             }
277           else
278             {
279               if (_g_main_poll_debug)
280                 g_print (" %p", (HANDLE) f->fd);
281               handle_to_fd[nhandles] = f;
282               handles[nhandles++] = (HANDLE) f->fd;
283             }
284         }
285       f->revents = 0;
286     }
287
288   if (_g_main_poll_debug)
289     g_print ("\n");
290
291   if (timeout == -1)
292     timeout = INFINITE;
293
294   /* Polling for several things? */
295   if (nhandles > 1 || (nhandles > 0 && msg_fd != NULL))
296     {
297       /* First check if one or several of them are immediately
298        * available
299        */
300       retval = poll_rest (msg_fd, handles, handle_to_fd, nhandles, 0);
301
302       /* If not, and we have a significant timeout, poll again with
303        * timeout then. Note that this will return indication for only
304        * one event, or only for messages.
305        */
306       if (retval == 0 && (timeout == INFINITE || timeout > 0))
307         retval = poll_rest (msg_fd, handles, handle_to_fd, nhandles, timeout);
308     }
309   else
310     {
311       /* Just polling for one thing, so no need to check first if
312        * available immediately
313        */
314       retval = poll_rest (msg_fd, handles, handle_to_fd, nhandles, timeout);
315     }
316
317   if (retval == -1)
318     for (f = fds; f < &fds[nfds]; ++f)
319       f->revents = 0;
320
321   return retval;
322 }
323
324 #else  /* !G_OS_WIN32 */
325
326 /* The following implementation of poll() comes from the GNU C Library.
327  * Copyright (C) 1994, 1996, 1997 Free Software Foundation, Inc.
328  */
329
330 #include <string.h> /* for bzero on BSD systems */
331
332 #ifdef HAVE_SYS_SELECT_H
333 #include <sys/select.h>
334 #endif /* HAVE_SYS_SELECT_H */
335
336 #ifndef NO_FD_SET
337 #  define SELECT_MASK fd_set
338 #else /* !NO_FD_SET */
339 #  ifndef _AIX
340 typedef long fd_mask;
341 #  endif /* _AIX */
342 #  ifdef _IBMR2
343 #    define SELECT_MASK void
344 #  else /* !_IBMR2 */
345 #    define SELECT_MASK int
346 #  endif /* !_IBMR2 */
347 #endif /* !NO_FD_SET */
348
349 gint
350 g_poll (GPollFD *fds,
351         guint    nfds,
352         gint     timeout)
353 {
354   struct timeval tv;
355   SELECT_MASK rset, wset, xset;
356   GPollFD *f;
357   int ready;
358   int maxfd = 0;
359
360   FD_ZERO (&rset);
361   FD_ZERO (&wset);
362   FD_ZERO (&xset);
363
364   for (f = fds; f < &fds[nfds]; ++f)
365     if (f->fd >= 0)
366       {
367         if (f->events & G_IO_IN)
368           FD_SET (f->fd, &rset);
369         if (f->events & G_IO_OUT)
370           FD_SET (f->fd, &wset);
371         if (f->events & G_IO_PRI)
372           FD_SET (f->fd, &xset);
373         if (f->fd > maxfd && (f->events & (G_IO_IN|G_IO_OUT|G_IO_PRI)))
374           maxfd = f->fd;
375       }
376
377   tv.tv_sec = timeout / 1000;
378   tv.tv_usec = (timeout % 1000) * 1000;
379
380   ready = select (maxfd + 1, &rset, &wset, &xset,
381                   timeout == -1 ? NULL : &tv);
382   if (ready > 0)
383     for (f = fds; f < &fds[nfds]; ++f)
384       {
385         f->revents = 0;
386         if (f->fd >= 0)
387           {
388             if (FD_ISSET (f->fd, &rset))
389               f->revents |= G_IO_IN;
390             if (FD_ISSET (f->fd, &wset))
391               f->revents |= G_IO_OUT;
392             if (FD_ISSET (f->fd, &xset))
393               f->revents |= G_IO_PRI;
394           }
395       }
396
397   return ready;
398 }
399
400 #endif /* !G_OS_WIN32 */
401
402 #endif  /* !HAVE_POLL */