BugĀ 587300 - g_cancellable_disconnect deadlock
[platform/upstream/glib.git] / gio / gcancellable.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <fcntl.h>
28 #include <gioerror.h>
29 #ifdef G_OS_WIN32
30 #include <windows.h>
31 #include <io.h>
32 #endif
33 #include "gcancellable.h"
34 #include "glibintl.h"
35
36 #include "gioalias.h"
37
38 /**
39  * SECTION:gcancellable
40  * @short_description: Thread-safe Operation Cancellation Stack
41  * @include: gio/gio.h
42  *
43  * GCancellable is a thread-safe operation cancellation stack used 
44  * throughout GIO to allow for cancellation of synchronous and
45  * asynchronous operations.
46  */
47
48 enum {
49   CANCELLED,
50   LAST_SIGNAL
51 };
52
53 struct _GCancellablePrivate
54 {
55   guint cancelled : 1;
56   guint cancelled_running : 1;
57   guint cancelled_running_waiting : 1;
58
59   guint fd_refcount;
60   int cancel_pipe[2];
61
62 #ifdef G_OS_WIN32
63   HANDLE event;
64 #endif
65 };
66
67 static guint signals[LAST_SIGNAL] = { 0 };
68
69 G_DEFINE_TYPE (GCancellable, g_cancellable, G_TYPE_OBJECT);
70
71 static GStaticPrivate current_cancellable = G_STATIC_PRIVATE_INIT;
72 G_LOCK_DEFINE_STATIC(cancellable);
73 static GCond *cancellable_cond = NULL;
74   
75 static void
76 g_cancellable_close_pipe (GCancellable *cancellable)
77 {
78   GCancellablePrivate *priv;
79   
80   priv = cancellable->priv;
81
82   if (priv->cancel_pipe[0] != -1)
83     {
84       close (priv->cancel_pipe[0]);
85       priv->cancel_pipe[0] = -1;
86     }
87   
88   if (priv->cancel_pipe[1] != -1)
89     {
90       close (priv->cancel_pipe[1]);
91       priv->cancel_pipe[1] = -1;
92     }
93
94 #ifdef G_OS_WIN32
95   if (priv->event)
96     {
97       CloseHandle (priv->event);
98       priv->event = NULL;
99     }
100 #endif
101 }
102
103 static void
104 g_cancellable_finalize (GObject *object)
105 {
106   GCancellable *cancellable = G_CANCELLABLE (object);
107
108   g_cancellable_close_pipe (cancellable);
109
110   G_OBJECT_CLASS (g_cancellable_parent_class)->finalize (object);
111 }
112
113 static void
114 g_cancellable_class_init (GCancellableClass *klass)
115 {
116   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
117
118   g_type_class_add_private (klass, sizeof (GCancellablePrivate));
119
120   if (cancellable_cond == NULL && g_thread_supported ())
121     cancellable_cond = g_cond_new ();
122   
123   gobject_class->finalize = g_cancellable_finalize;
124
125   /**
126    * GCancellable::cancelled:
127    * @cancellable: a #GCancellable.
128    * 
129    * Emitted when the operation has been cancelled.
130    * 
131    * Can be used by implementations of cancellable operations. If the
132    * operation is cancelled from another thread, the signal will be
133    * emitted in the thread that cancelled the operation, not the
134    * thread that is running the operation.
135    *
136    * Note that disconnecting from this signal (or any signal) in a
137    * multi-threaded program is prone to race conditions. For instance
138    * it is possible that a signal handler may be invoked even
139    * <emphasis>after</emphasis> a call to
140    * g_signal_handler_disconnect() for that handler has already
141    * returned.
142    * 
143    * There is also a problem when cancellation happen
144    * right before connecting to the signal. If this happens the
145    * signal will unexpectedly not be emitted, and checking before
146    * connecting to the signal leaves a race condition where this is
147    * still happening.
148    *
149    * In order to make it safe and easy to connect handlers there
150    * are two helper functions: g_cancellable_connect() and
151    * g_cancellable_disconnect() which protect against problems
152    * like this.
153    *
154    * An example of how to us this:
155    * |[
156    *     /<!-- -->* Make sure we don't do any unnecessary work if already cancelled *<!-- -->/
157    *     if (g_cancellable_set_error_if_cancelled (cancellable))
158    *       return;
159    *
160    *     /<!-- -->* Set up all the data needed to be able to
161    *      * handle cancellation of the operation *<!-- -->/
162    *     my_data = my_data_new (...);
163    *
164    *     id = 0;
165    *     if (cancellable)
166    *       id = g_cancellable_connect (cancellable,
167    *                                  G_CALLBACK (cancelled_handler)
168    *                                  data, NULL);
169    *
170    *     /<!-- -->* cancellable operation here... *<!-- -->/
171    *
172    *     g_cancellable_disconnect (cancellable, id);
173    *
174    *     /<!-- -->* cancelled_handler is never called after this, it
175    *      * is now safe to free the data *<!-- -->/
176    *     my_data_free (my_data);  
177    * ]|
178    *
179    * Note that the cancelled signal is emitted in the thread that
180    * the user cancelled from, which may be the main thread. So, the
181    * cancellable signal should not do something that can block.
182    */
183   signals[CANCELLED] =
184     g_signal_new (I_("cancelled"),
185                   G_TYPE_FROM_CLASS (gobject_class),
186                   G_SIGNAL_RUN_LAST,
187                   G_STRUCT_OFFSET (GCancellableClass, cancelled),
188                   NULL, NULL,
189                   g_cclosure_marshal_VOID__VOID,
190                   G_TYPE_NONE, 0);
191   
192 }
193
194 #ifndef G_OS_WIN32
195 static void
196 set_fd_nonblocking (int fd)
197 {
198 #ifdef F_GETFL
199   glong fcntl_flags;
200   fcntl_flags = fcntl (fd, F_GETFL);
201
202 #ifdef O_NONBLOCK
203   fcntl_flags |= O_NONBLOCK;
204 #else
205   fcntl_flags |= O_NDELAY;
206 #endif
207
208   fcntl (fd, F_SETFL, fcntl_flags);
209 #endif
210 }
211
212 static void
213 set_fd_close_exec (int fd)
214 {
215   int flags;
216
217   flags = fcntl (fd, F_GETFD, 0);
218   if (flags != -1 && (flags & FD_CLOEXEC) == 0)
219     {
220       flags |= FD_CLOEXEC;
221       fcntl (fd, F_SETFD, flags);
222     }
223 }
224
225
226 static void
227 g_cancellable_open_pipe (GCancellable *cancellable)
228 {
229   const char ch = 'x';
230   GCancellablePrivate *priv;
231
232   priv = cancellable->priv;
233   if (pipe (priv->cancel_pipe) == 0)
234     {
235       /* Make them nonblocking, just to be sure we don't block
236        * on errors and stuff
237        */
238       set_fd_nonblocking (priv->cancel_pipe[0]);
239       set_fd_nonblocking (priv->cancel_pipe[1]);
240       set_fd_close_exec (priv->cancel_pipe[0]);
241       set_fd_close_exec (priv->cancel_pipe[1]);
242       
243       if (priv->cancelled)
244         write (priv->cancel_pipe[1], &ch, 1);
245     }
246 }
247 #endif
248
249 static void
250 g_cancellable_init (GCancellable *cancellable)
251 {
252   cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
253                                                    G_TYPE_CANCELLABLE,
254                                                    GCancellablePrivate);
255   cancellable->priv->cancel_pipe[0] = -1;
256   cancellable->priv->cancel_pipe[1] = -1;
257 }
258
259 /**
260  * g_cancellable_new:
261  * 
262  * Creates a new #GCancellable object.
263  *
264  * Applications that want to start one or more operations
265  * that should be cancellable should create a #GCancellable
266  * and pass it to the operations.
267  *
268  * One #GCancellable can be used in multiple consecutive
269  * operations, but not in multiple concurrent operations.
270  *  
271  * Returns: a #GCancellable.
272  **/
273 GCancellable *
274 g_cancellable_new (void)
275 {
276   return g_object_new (G_TYPE_CANCELLABLE, NULL);
277 }
278
279 /**
280  * g_cancellable_push_current:
281  * @cancellable: a #GCancellable object
282  *
283  * Pushes @cancellable onto the cancellable stack. The current
284  * cancllable can then be recieved using g_cancellable_get_current().
285  *
286  * This is useful when implementing cancellable operations in
287  * code that does not allow you to pass down the cancellable object.
288  *
289  * This is typically called automatically by e.g. #GFile operations,
290  * so you rarely have to call this yourself.
291  **/
292 void
293 g_cancellable_push_current (GCancellable *cancellable)
294 {
295   GSList *l;
296
297   g_return_if_fail (cancellable != NULL);
298
299   l = g_static_private_get (&current_cancellable);
300   l = g_slist_prepend (l, cancellable);
301   g_static_private_set (&current_cancellable, l, NULL);
302 }
303
304 /**
305  * g_cancellable_pop_current:
306  * @cancellable: a #GCancellable object
307  *
308  * Pops @cancellable off the cancellable stack (verifying that @cancellable
309  * is on the top of the stack).
310  **/
311 void
312 g_cancellable_pop_current (GCancellable *cancellable)
313 {
314   GSList *l;
315
316   l = g_static_private_get (&current_cancellable);
317
318   g_return_if_fail (l != NULL);
319   g_return_if_fail (l->data == cancellable);
320
321   l = g_slist_delete_link (l, l);
322   g_static_private_set (&current_cancellable, l, NULL);
323 }
324
325 /**
326  * g_cancellable_get_current:
327  *
328  * Gets the top cancellable from the stack.
329  *
330  * Returns: a #GCancellable from the top of the stack, or %NULL
331  * if the stack is empty.
332  **/
333 GCancellable *
334 g_cancellable_get_current  (void)
335 {
336   GSList *l;
337
338   l = g_static_private_get (&current_cancellable);
339   if (l == NULL)
340     return NULL;
341
342   return G_CANCELLABLE (l->data);
343 }
344
345 /**
346  * g_cancellable_reset:
347  * @cancellable: a #GCancellable object.
348  * 
349  * Resets @cancellable to its uncancelled state. 
350  **/
351 void 
352 g_cancellable_reset (GCancellable *cancellable)
353 {
354   GCancellablePrivate *priv;
355
356   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
357
358   G_LOCK(cancellable);
359
360   priv = cancellable->priv;
361   
362   while (priv->cancelled_running)
363     {
364       priv->cancelled_running_waiting = TRUE;
365       g_cond_wait (cancellable_cond,
366                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
367     }
368   
369   if (priv->cancelled)
370     {
371       char ch;
372       
373     /* Make sure we're not leaving old cancel state around */
374       
375 #ifdef G_OS_WIN32
376       if (priv->event)
377         ResetEvent (priv->event);
378 #endif
379       if (priv->cancel_pipe[0] != -1)
380         read (priv->cancel_pipe[0], &ch, 1);
381       priv->cancelled = FALSE;
382     }
383   G_UNLOCK(cancellable);
384 }
385
386 /**
387  * g_cancellable_is_cancelled:
388  * @cancellable: a #GCancellable or NULL.
389  * 
390  * Checks if a cancellable job has been cancelled.
391  * 
392  * Returns: %TRUE if @cancellable is cancelled, 
393  * FALSE if called with %NULL or if item is not cancelled. 
394  **/
395 gboolean
396 g_cancellable_is_cancelled (GCancellable *cancellable)
397 {
398   return cancellable != NULL && cancellable->priv->cancelled;
399 }
400
401 /**
402  * g_cancellable_set_error_if_cancelled:
403  * @cancellable: a #GCancellable object.
404  * @error: #GError to append error state to.
405  * 
406  * If the @cancellable is cancelled, sets the error to notify
407  * that the operation was cancelled.
408  * 
409  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
410  **/
411 gboolean
412 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
413                                       GError       **error)
414 {
415   if (g_cancellable_is_cancelled (cancellable))
416     {
417       g_set_error_literal (error,
418                            G_IO_ERROR,
419                            G_IO_ERROR_CANCELLED,
420                            _("Operation was cancelled"));
421       return TRUE;
422     }
423   
424   return FALSE;
425 }
426
427 /**
428  * g_cancellable_get_fd:
429  * @cancellable: a #GCancellable.
430  * 
431  * Gets the file descriptor for a cancellable job. This can be used to
432  * implement cancellable operations on Unix systems. The returned fd will
433  * turn readable when @cancellable is cancelled.
434  *
435  * You are not supposed to read from the fd yourself, just check for
436  * readable status. Reading to unset the readable status is done
437  * with g_cancellable_reset().
438  * 
439  * After a successful return from this function, you should use 
440  * g_cancellable_release_fd() to free up resources allocated for 
441  * the returned file descriptor.
442  *
443  * See also g_cancellable_make_pollfd().
444  *
445  * Returns: A valid file descriptor. %-1 if the file descriptor 
446  * is not supported, or on errors. 
447  **/
448 int
449 g_cancellable_get_fd (GCancellable *cancellable)
450 {
451   GCancellablePrivate *priv;
452   int fd;
453
454   if (cancellable == NULL)
455     return -1;
456
457   priv = cancellable->priv;
458
459 #ifdef G_OS_WIN32
460   return -1;
461 #else
462   G_LOCK(cancellable);
463   if (priv->cancel_pipe[0] == -1)
464     g_cancellable_open_pipe (cancellable);
465   fd = priv->cancel_pipe[0];
466   if (fd != -1)
467     priv->fd_refcount++;
468   G_UNLOCK(cancellable);
469 #endif
470
471   return fd;
472 }
473
474 /**
475  * g_cancellable_make_pollfd:
476  * @cancellable: a #GCancellable or %NULL
477  * @pollfd: a pointer to a #GPollFD
478  * 
479  * Creates a #GPollFD corresponding to @cancellable; this can be passed
480  * to g_poll() and used to poll for cancellation. This is useful both
481  * for unix systems without a native poll and for portability to
482  * windows.
483  *
484  * When this function returns %TRUE, you should use 
485  * g_cancellable_release_fd() to free up resources allocated for the 
486  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
487  *
488  * If this function returns %FALSE, either no @cancellable was given or
489  * resource limits prevent this function from allocating the necessary 
490  * structures for polling. (On Linux, you will likely have reached 
491  * the maximum number of file descriptors.) The suggested way to handle
492  * these cases is to ignore the @cancellable.
493  *
494  * You are not supposed to read from the fd yourself, just check for
495  * readable status. Reading to unset the readable status is done
496  * with g_cancellable_reset().
497  *
498  * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
499  *          failure to prepare the cancellable.
500  * 
501  * Since: 2.22
502  **/
503 gboolean
504 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
505 {
506   GCancellablePrivate *priv;
507
508   g_return_val_if_fail (pollfd != NULL, FALSE);
509   if (cancellable == NULL)
510     return FALSE;
511   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
512
513 #ifdef G_OS_WIN32
514   priv = cancellable->priv;
515   G_LOCK(cancellable);
516   if (priv->event == NULL)
517     {
518       /* A manual reset anonymous event, starting unset */
519       priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
520       if (priv->event == NULL)
521         {
522           G_UNLOCK(cancellable);
523           return FALSE;
524         }
525       if (priv->cancelled)
526         SetEvent(priv->event);
527     }
528   priv->fd_refcount++;
529   G_UNLOCK(cancellable);
530
531   pollfd->fd = (gintptr)priv->event;
532 #else /* !G_OS_WIN32 */
533   {
534     int fd = g_cancellable_get_fd (cancellable);
535     if (fd == -1)
536       return FALSE;
537     pollfd->fd = fd;
538   }
539 #endif /* G_OS_WIN32 */
540   pollfd->events = G_IO_IN;
541   pollfd->revents = 0;
542
543   return TRUE;
544 }
545
546 /**
547  * g_cancellable_release_fd:
548  * @cancellable: a #GCancellable
549  *
550  * Releases a resources previously allocated by g_cancellable_get_fd()
551  * or g_cancellable_make_pollfd().
552  *
553  * For compatibility reasons with older releases, calling this function 
554  * is not strictly required, the resources will be automatically freed
555  * when the @cancellable is finalized. However, the @cancellable will
556  * block scarce file descriptors until it is finalized if this function
557  * is not called. This can cause the application to run out of file 
558  * descriptors when many #GCancellables are used at the same time.
559  * 
560  * Since: 2.22
561  **/
562 void
563 g_cancellable_release_fd (GCancellable *cancellable)
564 {
565   GCancellablePrivate *priv;
566
567   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
568   g_return_if_fail (cancellable->priv->fd_refcount > 0);
569
570   priv = cancellable->priv;
571
572   G_LOCK (cancellable);
573   priv->fd_refcount--;
574   if (priv->fd_refcount == 0)
575     g_cancellable_close_pipe (cancellable);
576   G_UNLOCK (cancellable);
577 }
578
579 /**
580  * g_cancellable_cancel:
581  * @cancellable: a #GCancellable object.
582  * 
583  * Will set @cancellable to cancelled, and will emit the
584  * #GCancellable::cancelled signal. (However, see the warning about
585  * race conditions in the documentation for that signal if you are
586  * planning to connect to it.)
587  *
588  * This function is thread-safe. In other words, you can safely call
589  * it from a thread other than the one running the operation that was
590  * passed the @cancellable.
591  *
592  * The convention within gio is that cancelling an asynchronous
593  * operation causes it to complete asynchronously. That is, if you
594  * cancel the operation from the same thread in which it is running,
595  * then the operation's #GAsyncReadyCallback will not be invoked until
596  * the application returns to the main loop.
597  **/
598 void
599 g_cancellable_cancel (GCancellable *cancellable)
600 {
601   const char ch = 'x';
602   gboolean cancel;
603   GCancellablePrivate *priv;
604
605   if (cancellable == NULL ||
606       cancellable->priv->cancelled)
607     return;
608
609   priv = cancellable->priv;
610   cancel = FALSE;
611
612   G_LOCK(cancellable);
613   cancel = TRUE;
614   priv->cancelled = TRUE;
615   priv->cancelled_running = TRUE;
616 #ifdef G_OS_WIN32
617   if (priv->event)
618     SetEvent (priv->event);
619 #endif
620   if (priv->cancel_pipe[1] != -1)
621     write (priv->cancel_pipe[1], &ch, 1);
622   G_UNLOCK(cancellable);
623
624   if (cancel)
625     {
626       g_object_ref (cancellable);
627       g_signal_emit (cancellable, signals[CANCELLED], 0);
628
629       G_LOCK(cancellable);
630
631       priv->cancelled_running = FALSE;
632       if (priv->cancelled_running_waiting)
633         g_cond_broadcast (cancellable_cond);
634       priv->cancelled_running_waiting = FALSE;
635
636       G_UNLOCK(cancellable);
637
638       g_object_unref (cancellable);
639     }
640 }
641
642 /**
643  * g_cancellable_connect:
644  * @cancellable: A #GCancellable.
645  * @callback: The #GCallback to connect.
646  * @data: Data to pass to @callback.
647  * @data_destroy_func: Free function for @data or %NULL.
648  *
649  * Convenience function to connect to the #GCancellable::cancelled
650  * signal. Also handles the race condition that may happen
651  * if the cancellable is cancelled right before connecting.
652  *
653  * @callback is called at most once, either directly at the
654  * time of the connect if @cancellable is already cancelled,
655  * or when @cancellable is cancelled in some thread.
656  *
657  * @data_destroy_func will be called when the handler is
658  * disconnected, or immediately if the cancellable is already
659  * cancelled.
660  *
661  * See #GCancellable::cancelled for details on how to use this.
662  *
663  * Returns: The id of the signal handler or 0 if @cancellable has already
664  *          been cancelled.
665  *
666  * Since: 2.22
667  */
668 gulong
669 g_cancellable_connect (GCancellable   *cancellable,
670                        GCallback       callback,
671                        gpointer        data,
672                        GDestroyNotify  data_destroy_func)
673 {
674   gulong id;
675
676   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
677
678   G_LOCK (cancellable);
679
680   if (cancellable->priv->cancelled)
681     {
682       void (*_callback) (GCancellable *cancellable,
683                          gpointer      user_data);
684
685       _callback = (void *)callback;
686       id = 0;
687
688       _callback (cancellable, data);
689
690       if (data_destroy_func)
691         data_destroy_func (data);
692     }
693   else
694     {
695       id = g_signal_connect_data (cancellable, "cancelled",
696                                   callback, data,
697                                   (GClosureNotify) data_destroy_func,
698                                   0);
699     }
700   G_UNLOCK (cancellable);
701
702   return id;
703 }
704
705 /**
706  * g_cancellable_disconnect:
707  * @cancellable: A #GCancellable or %NULL.
708  * @handler_id: Handler id of the handler to be disconnected, or %0.
709  *
710  * Disconnects a handler from a cancellable instance similar to
711  * g_signal_handler_disconnect().  Additionally, in the event that a
712  * signal handler is currently running, this call will block until the
713  * handler has finished.  Calling this function from a
714  * #GCancellable::cancelled signal handler will therefore result in a
715  * deadlock.
716  *
717  * This avoids a race condition where a thread cancels at the
718  * same time as the cancellable operation is finished and the
719  * signal handler is removed. See #GCancellable::cancelled for
720  * details on how to use this.
721  *
722  * If @cancellable is %NULL or @handler_id is %0 this function does
723  * nothing.
724  *
725  * Since: 2.22
726  */
727 void
728 g_cancellable_disconnect (GCancellable  *cancellable,
729                           gulong         handler_id)
730 {
731   GCancellablePrivate *priv;
732
733   if (handler_id == 0 ||  cancellable == NULL)
734     return;
735
736   G_LOCK (cancellable);
737
738   priv = cancellable->priv;
739
740   while (priv->cancelled_running)
741     {
742       priv->cancelled_running_waiting = TRUE;
743       g_cond_wait (cancellable_cond,
744                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
745     }
746
747   g_signal_handler_disconnect (cancellable, handler_id);
748   G_UNLOCK (cancellable);
749 }
750
751 #define __G_CANCELLABLE_C__
752 #include "gioaliasdef.c"