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