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