_dbus_loop_new: don't crash on OOM allocating socket set
[platform/upstream/dbus.git] / dbus / dbus-mainloop.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-mainloop.c  Main loop utility
3  *
4  * Copyright © 2003, 2004  Red Hat, Inc.
5  * Copyright © 2011 Nokia Corporation
6  *
7  * Licensed under the Academic Free License version 2.1
8  * 
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22  *
23  */
24
25 #include <config.h>
26 #include "dbus-mainloop.h"
27
28 #ifndef DOXYGEN_SHOULD_SKIP_THIS
29
30 #include <dbus/dbus-hash.h>
31 #include <dbus/dbus-list.h>
32 #include <dbus/dbus-socket-set.h>
33 #include <dbus/dbus-watch.h>
34
35 #define MAINLOOP_SPEW 0
36
37 #if MAINLOOP_SPEW
38 #ifdef DBUS_ENABLE_VERBOSE_MODE
39 static const char*
40 watch_flags_to_string (int flags)
41 {
42   const char *watch_type;
43
44   if ((flags & DBUS_WATCH_READABLE) &&
45       (flags & DBUS_WATCH_WRITABLE))
46     watch_type = "readwrite";
47   else if (flags & DBUS_WATCH_READABLE)
48     watch_type = "read";
49   else if (flags & DBUS_WATCH_WRITABLE)
50     watch_type = "write";
51   else
52     watch_type = "not read or write";
53   return watch_type;
54 }
55 #endif /* DBUS_ENABLE_VERBOSE_MODE */
56 #endif /* MAINLOOP_SPEW */
57
58 struct DBusLoop
59 {
60   int refcount;
61   /** fd => dbus_malloc'd DBusList ** of references to DBusWatch */
62   DBusHashTable *watches;
63   DBusSocketSet *socket_set;
64   DBusList *timeouts;
65   int callback_list_serial;
66   int watch_count;
67   int timeout_count;
68   int depth; /**< number of recursive runs */
69   DBusList *need_dispatch;
70   /** TRUE if we will skip a watch next time because it was OOM; becomes
71    * FALSE between polling, and dealing with the results of the poll */
72   unsigned oom_watch_pending : 1;
73 };
74
75 typedef struct
76 {
77   int refcount;
78   DBusTimeout *timeout;
79   unsigned long last_tv_sec;
80   unsigned long last_tv_usec;
81 } TimeoutCallback;
82
83 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
84
85 static TimeoutCallback*
86 timeout_callback_new (DBusTimeout         *timeout)
87 {
88   TimeoutCallback *cb;
89
90   cb = dbus_new (TimeoutCallback, 1);
91   if (cb == NULL)
92     return NULL;
93
94   cb->timeout = timeout;
95   _dbus_get_current_time (&cb->last_tv_sec,
96                           &cb->last_tv_usec);
97   cb->refcount = 1;
98   return cb;
99 }
100
101 static TimeoutCallback *
102 timeout_callback_ref (TimeoutCallback *cb)
103 {
104   _dbus_assert (cb->refcount > 0);
105   
106   cb->refcount += 1;
107
108   return cb;
109 }
110
111 static void
112 timeout_callback_unref (TimeoutCallback *cb)
113 {
114   _dbus_assert (cb->refcount > 0);
115
116   cb->refcount -= 1;
117
118   if (cb->refcount == 0)
119     {
120       dbus_free (cb);
121     }
122 }
123
124 static void
125 free_watch_table_entry (void *data)
126 {
127   DBusList **watches = data;
128   DBusWatch *watch;
129
130   /* DBusHashTable sometimes calls free_function(NULL) even if you never
131    * have NULL as a value */
132   if (watches == NULL)
133     return;
134
135   for (watch = _dbus_list_pop_first (watches);
136       watch != NULL;
137       watch = _dbus_list_pop_first (watches))
138     {
139       _dbus_watch_unref (watch);
140     }
141
142   _dbus_assert (*watches == NULL);
143   dbus_free (watches);
144 }
145
146 DBusLoop*
147 _dbus_loop_new (void)
148 {
149   DBusLoop *loop;
150
151   loop = dbus_new0 (DBusLoop, 1);
152   if (loop == NULL)
153     return NULL;
154
155   loop->watches = _dbus_hash_table_new (DBUS_HASH_INT, NULL,
156                                         free_watch_table_entry);
157
158   loop->socket_set = _dbus_socket_set_new (0);
159
160   if (loop->watches == NULL || loop->socket_set == NULL)
161     {
162       if (loop->watches != NULL)
163         _dbus_hash_table_unref (loop->watches);
164
165       if (loop->socket_set != NULL)
166         _dbus_socket_set_free (loop->socket_set);
167
168       dbus_free (loop);
169       return NULL;
170     }
171
172   loop->refcount = 1;
173
174   return loop;
175 }
176
177 DBusLoop *
178 _dbus_loop_ref (DBusLoop *loop)
179 {
180   _dbus_assert (loop != NULL);
181   _dbus_assert (loop->refcount > 0);
182
183   loop->refcount += 1;
184
185   return loop;
186 }
187
188 void
189 _dbus_loop_unref (DBusLoop *loop)
190 {
191   _dbus_assert (loop != NULL);
192   _dbus_assert (loop->refcount > 0);
193
194   loop->refcount -= 1;
195   if (loop->refcount == 0)
196     {
197       while (loop->need_dispatch)
198         {
199           DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
200
201           dbus_connection_unref (connection);
202         }
203
204       _dbus_hash_table_unref (loop->watches);
205       _dbus_socket_set_free (loop->socket_set);
206       dbus_free (loop);
207     }
208 }
209
210 static DBusList **
211 ensure_watch_table_entry (DBusLoop *loop,
212                           int       fd)
213 {
214   DBusList **watches;
215
216   watches = _dbus_hash_table_lookup_int (loop->watches, fd);
217
218   if (watches == NULL)
219     {
220       watches = dbus_new0 (DBusList *, 1);
221
222       if (watches == NULL)
223         return watches;
224
225       if (!_dbus_hash_table_insert_int (loop->watches, fd, watches))
226         {
227           dbus_free (watches);
228           watches = NULL;
229         }
230     }
231
232   return watches;
233 }
234
235 static void
236 cull_watches_for_invalid_fd (DBusLoop  *loop,
237                              int        fd)
238 {
239   DBusList *link;
240   DBusList *next;
241   DBusList **watches;
242
243   _dbus_warn ("invalid request, socket fd %d not open\n", fd);
244   watches = _dbus_hash_table_lookup_int (loop->watches, fd);
245
246   if (watches != NULL)
247     {
248       for (link = _dbus_list_get_first_link (watches);
249           link != NULL;
250           link = _dbus_list_get_next_link (watches, link))
251         _dbus_watch_invalidate (link->data);
252     }
253
254   _dbus_hash_table_remove_int (loop->watches, fd);
255 }
256
257 static dbus_bool_t
258 gc_watch_table_entry (DBusLoop  *loop,
259                       DBusList **watches,
260                       int        fd)
261 {
262   /* If watches is already NULL we have nothing to do */
263   if (watches == NULL)
264     return FALSE;
265
266   /* We can't GC hash table entries if they're non-empty lists */
267   if (*watches != NULL)
268     return FALSE;
269
270   _dbus_hash_table_remove_int (loop->watches, fd);
271   return TRUE;
272 }
273
274 static void
275 refresh_watches_for_fd (DBusLoop  *loop,
276                         DBusList **watches,
277                         int        fd)
278 {
279   DBusList *link;
280   unsigned int flags = 0;
281   dbus_bool_t interested;
282
283   _dbus_assert (fd != -1);
284
285   if (watches == NULL)
286     watches = _dbus_hash_table_lookup_int (loop->watches, fd);
287
288   /* we allocated this in the first _dbus_loop_add_watch for the fd, and keep
289    * it until there are none left */
290   _dbus_assert (watches != NULL);
291
292   for (link = _dbus_list_get_first_link (watches);
293       link != NULL;
294       link = _dbus_list_get_next_link (watches, link))
295     {
296       if (dbus_watch_get_enabled (link->data) &&
297           !_dbus_watch_get_oom_last_time (link->data))
298         {
299           flags |= dbus_watch_get_flags (link->data);
300           interested = TRUE;
301         }
302     }
303
304   if (interested)
305     _dbus_socket_set_enable (loop->socket_set, fd, flags);
306   else
307     _dbus_socket_set_disable (loop->socket_set, fd);
308 }
309
310 dbus_bool_t
311 _dbus_loop_add_watch (DBusLoop  *loop,
312                       DBusWatch *watch)
313 {
314   int fd;
315   DBusList **watches;
316
317   fd = dbus_watch_get_socket (watch);
318   _dbus_assert (fd != -1);
319
320   watches = ensure_watch_table_entry (loop, fd);
321
322   if (watches == NULL)
323     return FALSE;
324
325   if (!_dbus_list_append (watches, _dbus_watch_ref (watch)))
326     {
327       _dbus_watch_unref (watch);
328       gc_watch_table_entry (loop, watches, fd);
329
330       return FALSE;
331     }
332
333   if (_dbus_list_length_is_one (watches))
334     {
335       if (!_dbus_socket_set_add (loop->socket_set, fd,
336                                  dbus_watch_get_flags (watch),
337                                  dbus_watch_get_enabled (watch)))
338         {
339           _dbus_hash_table_remove_int (loop->watches, fd);
340           return FALSE;
341         }
342     }
343   else
344     {
345       /* we're modifying, not adding, which can't fail with OOM */
346       refresh_watches_for_fd (loop, watches, fd);
347     }
348
349   loop->callback_list_serial += 1;
350   loop->watch_count += 1;
351   return TRUE;
352 }
353
354 void
355 _dbus_loop_toggle_watch (DBusLoop          *loop,
356                          DBusWatch         *watch)
357 {
358   refresh_watches_for_fd (loop, NULL, dbus_watch_get_socket (watch));
359 }
360
361 void
362 _dbus_loop_remove_watch (DBusLoop         *loop,
363                          DBusWatch        *watch)
364 {
365   DBusList **watches;
366   DBusList *link;
367   int fd;
368
369   /* This relies on people removing watches before they invalidate them,
370    * which has been safe since fd.o #33336 was fixed. Assert about it
371    * so we don't regress. */
372   fd = dbus_watch_get_socket (watch);
373   _dbus_assert (fd != -1);
374
375   watches = _dbus_hash_table_lookup_int (loop->watches, fd);
376
377   if (watches != NULL)
378     {
379       link = _dbus_list_get_first_link (watches);
380       while (link != NULL)
381         {
382           DBusList *next = _dbus_list_get_next_link (watches, link);
383           DBusWatch *this = link->data;
384
385           if (this == watch)
386             {
387               _dbus_list_remove_link (watches, link);
388               loop->callback_list_serial += 1;
389               loop->watch_count -= 1;
390               _dbus_watch_unref (this);
391
392               /* if that was the last watch for that fd, drop the hash table
393                * entry, and stop reserving space for it in the socket set */
394               if (gc_watch_table_entry (loop, watches, fd))
395                 {
396                   _dbus_socket_set_remove (loop->socket_set, fd);
397                 }
398
399               return;
400             }
401
402           link = next;
403          }
404      }
405
406   _dbus_warn ("could not find watch %p to remove\n", watch);
407 }
408
409 dbus_bool_t
410 _dbus_loop_add_timeout (DBusLoop           *loop,
411                         DBusTimeout        *timeout)
412 {
413   TimeoutCallback *tcb;
414
415   tcb = timeout_callback_new (timeout);
416   if (tcb == NULL)
417     return FALSE;
418
419   if (_dbus_list_append (&loop->timeouts, tcb))
420     {
421       loop->callback_list_serial += 1;
422       loop->timeout_count += 1;
423     }
424   else
425     {
426       timeout_callback_unref (tcb);
427       return FALSE;
428     }
429   
430   return TRUE;
431 }
432
433 void
434 _dbus_loop_remove_timeout (DBusLoop           *loop,
435                            DBusTimeout        *timeout)
436 {
437   DBusList *link;
438   
439   link = _dbus_list_get_first_link (&loop->timeouts);
440   while (link != NULL)
441     {
442       DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
443       TimeoutCallback *this = link->data;
444
445       if (this->timeout == timeout)
446         {
447           _dbus_list_remove_link (&loop->timeouts, link);
448           loop->callback_list_serial += 1;
449           loop->timeout_count -= 1;
450           timeout_callback_unref (this);
451
452           return;
453         }
454       
455       link = next;
456     }
457
458   _dbus_warn ("could not find timeout %p to remove\n", timeout);
459 }
460
461 /* Convolutions from GLib, there really must be a better way
462  * to do this.
463  */
464 static dbus_bool_t
465 check_timeout (unsigned long    tv_sec,
466                unsigned long    tv_usec,
467                TimeoutCallback *tcb,
468                int             *timeout)
469 {
470   long sec_remaining;
471   long msec_remaining;
472   unsigned long expiration_tv_sec;
473   unsigned long expiration_tv_usec;
474   long interval_seconds;
475   long interval_milliseconds;
476   int interval;
477
478   /* I'm pretty sure this function could suck (a lot) less */
479   
480   interval = dbus_timeout_get_interval (tcb->timeout);
481   
482   interval_seconds = interval / 1000L;
483   interval_milliseconds = interval % 1000L;
484   
485   expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
486   expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
487   if (expiration_tv_usec >= 1000000)
488     {
489       expiration_tv_usec -= 1000000;
490       expiration_tv_sec += 1;
491     }
492   
493   sec_remaining = expiration_tv_sec - tv_sec;
494   /* need to force this to be signed, as it is intended to sometimes
495    * produce a negative result
496    */
497   msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
498
499 #if MAINLOOP_SPEW
500   _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
501                  interval_seconds,
502                  interval_milliseconds);
503   _dbus_verbose ("Now is  %lu seconds %lu usecs\n",
504                  tv_sec, tv_usec);
505   _dbus_verbose ("Last is %lu seconds %lu usecs\n",
506                  tcb->last_tv_sec, tcb->last_tv_usec);
507   _dbus_verbose ("Exp is  %lu seconds %lu usecs\n",
508                  expiration_tv_sec, expiration_tv_usec);
509   _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
510                  sec_remaining, msec_remaining);
511 #endif
512   
513   /* We do the following in a rather convoluted fashion to deal with
514    * the fact that we don't have an integral type big enough to hold
515    * the difference of two timevals in milliseconds.
516    */
517   if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
518     {
519       *timeout = 0;
520     }
521   else
522     {
523       if (msec_remaining < 0)
524         {
525           msec_remaining += 1000;
526           sec_remaining -= 1;
527         }
528
529       if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
530           msec_remaining > _DBUS_INT_MAX)
531         *timeout = _DBUS_INT_MAX;
532       else
533         *timeout = sec_remaining * 1000 + msec_remaining;        
534     }
535
536   if (*timeout > interval)
537     {
538       /* This indicates that the system clock probably moved backward */
539       _dbus_verbose ("System clock set backward! Resetting timeout.\n");
540       
541       tcb->last_tv_sec = tv_sec;
542       tcb->last_tv_usec = tv_usec;
543
544       *timeout = interval;
545     }
546   
547 #if MAINLOOP_SPEW
548   _dbus_verbose ("  timeout expires in %d milliseconds\n", *timeout);
549 #endif
550   
551   return *timeout == 0;
552 }
553
554 dbus_bool_t
555 _dbus_loop_dispatch (DBusLoop *loop)
556 {
557
558 #if MAINLOOP_SPEW
559   _dbus_verbose ("  %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
560 #endif
561   
562   if (loop->need_dispatch == NULL)
563     return FALSE;
564   
565  next:
566   while (loop->need_dispatch != NULL)
567     {
568       DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
569       
570       while (TRUE)
571         {
572           DBusDispatchStatus status;
573           
574           status = dbus_connection_dispatch (connection);
575
576           if (status == DBUS_DISPATCH_COMPLETE)
577             {
578               dbus_connection_unref (connection);
579               goto next;
580             }
581           else
582             {
583               if (status == DBUS_DISPATCH_NEED_MEMORY)
584                 _dbus_wait_for_memory ();
585             }
586         }
587     }
588
589   return TRUE;
590 }
591
592 dbus_bool_t
593 _dbus_loop_queue_dispatch (DBusLoop       *loop,
594                            DBusConnection *connection)
595 {
596   if (_dbus_list_append (&loop->need_dispatch, connection))
597     {
598       dbus_connection_ref (connection);
599       return TRUE;
600     }
601   else
602     return FALSE;
603 }
604
605 /* Returns TRUE if we invoked any timeouts or have ready file
606  * descriptors, which is just used in test code as a debug hack
607  */
608
609 dbus_bool_t
610 _dbus_loop_iterate (DBusLoop     *loop,
611                     dbus_bool_t   block)
612 {  
613 #define N_STACK_DESCRIPTORS 64
614   dbus_bool_t retval;
615   DBusSocketEvent ready_fds[N_STACK_DESCRIPTORS];
616   int i;
617   DBusList *link;
618   int n_ready;
619   int initial_serial;
620   long timeout;
621   int orig_depth;
622
623   retval = FALSE;      
624
625   orig_depth = loop->depth;
626   
627 #if MAINLOOP_SPEW
628   _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
629                  block, loop->depth, loop->timeout_count, loop->watch_count);
630 #endif
631
632   if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
633       loop->timeouts == NULL)
634     goto next_iteration;
635
636   timeout = -1;
637   if (loop->timeout_count > 0)
638     {
639       unsigned long tv_sec;
640       unsigned long tv_usec;
641       
642       _dbus_get_current_time (&tv_sec, &tv_usec);
643
644       link = _dbus_list_get_first_link (&loop->timeouts);
645       while (link != NULL)
646         {
647           DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
648           TimeoutCallback *tcb = link->data;
649
650           if (dbus_timeout_get_enabled (tcb->timeout))
651             {
652               int msecs_remaining;
653
654               check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
655
656               if (timeout < 0)
657                 timeout = msecs_remaining;
658               else
659                 timeout = MIN (msecs_remaining, timeout);
660
661 #if MAINLOOP_SPEW
662               _dbus_verbose ("  timeout added, %d remaining, aggregate timeout %ld\n",
663                              msecs_remaining, timeout);
664 #endif
665               
666               _dbus_assert (timeout >= 0);
667                   
668               if (timeout == 0)
669                 break; /* it's not going to get shorter... */
670             }
671 #if MAINLOOP_SPEW
672           else
673             {
674               _dbus_verbose ("  skipping disabled timeout\n");
675             }
676 #endif
677           
678           link = next;
679         }
680     }
681
682   /* Never block if we have stuff to dispatch */
683   if (!block || loop->need_dispatch != NULL)
684     {
685       timeout = 0;
686 #if MAINLOOP_SPEW
687       _dbus_verbose ("  timeout is 0 as we aren't blocking\n");
688 #endif
689     }
690
691   /* if a watch was OOM last time, don't wait longer than the OOM
692    * wait to re-enable it
693    */
694   if (loop->oom_watch_pending)
695     timeout = MIN (timeout, _dbus_get_oom_wait ());
696
697 #if MAINLOOP_SPEW
698   _dbus_verbose ("  polling on %d descriptors timeout %ld\n", n_fds, timeout);
699 #endif
700
701   n_ready = _dbus_socket_set_poll (loop->socket_set, ready_fds,
702                                    _DBUS_N_ELEMENTS (ready_fds), timeout);
703
704   /* re-enable any watches we skipped this time */
705   if (loop->oom_watch_pending)
706     {
707       DBusHashIter hash_iter;
708
709       loop->oom_watch_pending = FALSE;
710
711       _dbus_hash_iter_init (loop->watches, &hash_iter);
712
713       while (_dbus_hash_iter_next (&hash_iter))
714         {
715           DBusList **watches;
716           int fd;
717           dbus_bool_t changed;
718
719           changed = FALSE;
720           fd = _dbus_hash_iter_get_int_key (&hash_iter);
721           watches = _dbus_hash_iter_get_value (&hash_iter);
722
723           for (link = _dbus_list_get_first_link (watches);
724               link != NULL;
725               link = _dbus_list_get_next_link (watches, link))
726             {
727               DBusWatch *watch = link->data;
728
729               if (_dbus_watch_get_oom_last_time (watch))
730                 {
731                   _dbus_watch_set_oom_last_time (watch, FALSE);
732                   changed = TRUE;
733                 }
734             }
735
736           if (changed)
737             refresh_watches_for_fd (loop, watches, fd);
738         }
739
740       retval = TRUE; /* return TRUE here to keep the loop going,
741                       * since we don't know the watch was inactive */
742     }
743
744   initial_serial = loop->callback_list_serial;
745
746   if (loop->timeout_count > 0)
747     {
748       unsigned long tv_sec;
749       unsigned long tv_usec;
750
751       _dbus_get_current_time (&tv_sec, &tv_usec);
752
753       /* It'd be nice to avoid this O(n) thingy here */
754       link = _dbus_list_get_first_link (&loop->timeouts);
755       while (link != NULL)
756         {
757           DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
758           TimeoutCallback *tcb = link->data;
759
760           if (initial_serial != loop->callback_list_serial)
761             goto next_iteration;
762
763           if (loop->depth != orig_depth)
764             goto next_iteration;
765
766           if (dbus_timeout_get_enabled (tcb->timeout))
767             {
768               int msecs_remaining;
769               
770               if (check_timeout (tv_sec, tv_usec,
771                                  tcb, &msecs_remaining))
772                 {
773                   /* Save last callback time and fire this timeout */
774                   tcb->last_tv_sec = tv_sec;
775                   tcb->last_tv_usec = tv_usec;
776
777 #if MAINLOOP_SPEW
778                   _dbus_verbose ("  invoking timeout\n");
779 #endif
780
781                   /* can theoretically return FALSE on OOM, but we just
782                    * let it fire again later - in practice that's what
783                    * every wrapper callback in dbus-daemon used to do */
784                   dbus_timeout_handle (tcb->timeout);
785
786                   retval = TRUE;
787                 }
788               else
789                 {
790 #if MAINLOOP_SPEW
791                   _dbus_verbose ("  timeout has not expired\n");
792 #endif
793                 }
794             }
795 #if MAINLOOP_SPEW
796           else
797             {
798               _dbus_verbose ("  skipping invocation of disabled timeout\n");
799             }
800 #endif
801
802           link = next;
803         }
804     }
805
806   if (n_ready > 0)
807     {
808       for (i = 0; i < n_ready; i++)
809         {
810           DBusList **watches;
811           DBusList *next;
812           unsigned int condition;
813           dbus_bool_t any_oom;
814
815           /* FIXME I think this "restart if we change the watches"
816            * approach could result in starving watches
817            * toward the end of the list.
818            */
819           if (initial_serial != loop->callback_list_serial)
820             goto next_iteration;
821
822           if (loop->depth != orig_depth)
823             goto next_iteration;
824
825           _dbus_assert (ready_fds[i].flags != 0);
826
827           if (_DBUS_UNLIKELY (ready_fds[i].flags & _DBUS_WATCH_NVAL))
828             {
829               cull_watches_for_invalid_fd (loop, ready_fds[i].fd);
830               goto next_iteration;
831             }
832
833           condition = ready_fds[i].flags;
834           _dbus_assert ((condition & _DBUS_WATCH_NVAL) == 0);
835
836           /* condition may still be 0 if we got some
837            * weird POLLFOO thing like POLLWRBAND
838            */
839           if (condition == 0)
840             continue;
841
842           watches = _dbus_hash_table_lookup_int (loop->watches,
843                                                  ready_fds[i].fd);
844
845           if (watches == NULL)
846             continue;
847
848           any_oom = FALSE;
849
850           for (link = _dbus_list_get_first_link (watches);
851               link != NULL;
852               link = next)
853             {
854               DBusWatch *watch = link->data;
855
856               next = _dbus_list_get_next_link (watches, link);
857
858               if (dbus_watch_get_enabled (watch))
859                 {
860                   dbus_bool_t oom;
861
862                   oom = !dbus_watch_handle (watch, condition);
863
864                   if (oom)
865                     {
866                       _dbus_watch_set_oom_last_time (watch, TRUE);
867                       loop->oom_watch_pending = TRUE;
868                       any_oom = TRUE;
869                     }
870
871 #if MAINLOOP_SPEW
872                   _dbus_verbose ("  Invoked watch, oom = %d\n", oom);
873 #endif
874                   retval = TRUE;
875
876                   /* We re-check this every time, in case the callback
877                    * added/removed watches, which might make our position in
878                    * the linked list invalid. See the FIXME above. */
879                   if (initial_serial != loop->callback_list_serial ||
880                       loop->depth != orig_depth)
881                     {
882                       if (any_oom)
883                         refresh_watches_for_fd (loop, NULL, ready_fds[i].fd);
884
885                       goto next_iteration;
886                     }
887                 }
888             }
889
890           if (any_oom)
891             refresh_watches_for_fd (loop, watches, ready_fds[i].fd);
892         }
893     }
894       
895  next_iteration:
896 #if MAINLOOP_SPEW
897   _dbus_verbose ("  moving to next iteration\n");
898 #endif
899
900   if (_dbus_loop_dispatch (loop))
901     retval = TRUE;
902   
903 #if MAINLOOP_SPEW
904   _dbus_verbose ("Returning %d\n", retval);
905 #endif
906   
907   return retval;
908 }
909
910 void
911 _dbus_loop_run (DBusLoop *loop)
912 {
913   int our_exit_depth;
914
915   _dbus_assert (loop->depth >= 0);
916   
917   _dbus_loop_ref (loop);
918   
919   our_exit_depth = loop->depth;
920   loop->depth += 1;
921
922   _dbus_verbose ("Running main loop, depth %d -> %d\n",
923                  loop->depth - 1, loop->depth);
924   
925   while (loop->depth != our_exit_depth)
926     _dbus_loop_iterate (loop, TRUE);
927
928   _dbus_loop_unref (loop);
929 }
930
931 void
932 _dbus_loop_quit (DBusLoop *loop)
933 {
934   _dbus_assert (loop->depth > 0);  
935   
936   loop->depth -= 1;
937
938   _dbus_verbose ("Quit main loop, depth %d -> %d\n",
939                  loop->depth + 1, loop->depth);
940 }
941
942 int
943 _dbus_get_oom_wait (void)
944 {
945 #ifdef DBUS_BUILD_TESTS
946   /* make tests go fast */
947   return 0;
948 #else
949   return 500;
950 #endif
951 }
952
953 void
954 _dbus_wait_for_memory (void)
955 {
956   _dbus_verbose ("Waiting for more memory\n");
957   _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
958 }
959
960 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */