Add a lot of missing annotations
[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 <errno.h>
28 #include <fcntl.h>
29 #include <gioerror.h>
30 #ifdef G_OS_WIN32
31 #include <windows.h>
32 #include <io.h>
33 #endif
34 #include "gcancellable.h"
35 #include "glibintl.h"
36
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   GCancellablePrivate *priv;
230
231   priv = cancellable->priv;
232   if (pipe (priv->cancel_pipe) == 0)
233     {
234       /* Make them nonblocking, just to be sure we don't block
235        * on errors and stuff
236        */
237       set_fd_nonblocking (priv->cancel_pipe[0]);
238       set_fd_nonblocking (priv->cancel_pipe[1]);
239       set_fd_close_exec (priv->cancel_pipe[0]);
240       set_fd_close_exec (priv->cancel_pipe[1]);
241       
242       if (priv->cancelled)
243         {
244           const char ch = 'x';
245           gssize c;
246
247           do
248             c = write (priv->cancel_pipe[1], &ch, 1);
249           while (c == -1 && errno == EINTR);
250         }
251     }
252 }
253 #endif
254
255 static void
256 g_cancellable_init (GCancellable *cancellable)
257 {
258   cancellable->priv = G_TYPE_INSTANCE_GET_PRIVATE (cancellable,
259                                                    G_TYPE_CANCELLABLE,
260                                                    GCancellablePrivate);
261   cancellable->priv->cancel_pipe[0] = -1;
262   cancellable->priv->cancel_pipe[1] = -1;
263 }
264
265 /**
266  * g_cancellable_new:
267  * 
268  * Creates a new #GCancellable object.
269  *
270  * Applications that want to start one or more operations
271  * that should be cancellable should create a #GCancellable
272  * and pass it to the operations.
273  *
274  * One #GCancellable can be used in multiple consecutive
275  * operations, but not in multiple concurrent operations.
276  *  
277  * Returns: a #GCancellable.
278  **/
279 GCancellable *
280 g_cancellable_new (void)
281 {
282   return g_object_new (G_TYPE_CANCELLABLE, NULL);
283 }
284
285 /**
286  * g_cancellable_push_current:
287  * @cancellable: a #GCancellable object
288  *
289  * Pushes @cancellable onto the cancellable stack. The current
290  * cancllable can then be recieved using g_cancellable_get_current().
291  *
292  * This is useful when implementing cancellable operations in
293  * code that does not allow you to pass down the cancellable object.
294  *
295  * This is typically called automatically by e.g. #GFile operations,
296  * so you rarely have to call this yourself.
297  **/
298 void
299 g_cancellable_push_current (GCancellable *cancellable)
300 {
301   GSList *l;
302
303   g_return_if_fail (cancellable != NULL);
304
305   l = g_static_private_get (&current_cancellable);
306   l = g_slist_prepend (l, cancellable);
307   g_static_private_set (&current_cancellable, l, NULL);
308 }
309
310 /**
311  * g_cancellable_pop_current:
312  * @cancellable: a #GCancellable object
313  *
314  * Pops @cancellable off the cancellable stack (verifying that @cancellable
315  * is on the top of the stack).
316  **/
317 void
318 g_cancellable_pop_current (GCancellable *cancellable)
319 {
320   GSList *l;
321
322   l = g_static_private_get (&current_cancellable);
323
324   g_return_if_fail (l != NULL);
325   g_return_if_fail (l->data == cancellable);
326
327   l = g_slist_delete_link (l, l);
328   g_static_private_set (&current_cancellable, l, NULL);
329 }
330
331 /**
332  * g_cancellable_get_current:
333  *
334  * Gets the top cancellable from the stack.
335  *
336  * Returns: (transfer none): a #GCancellable from the top of the stack, or %NULL
337  * if the stack is empty.
338  **/
339 GCancellable *
340 g_cancellable_get_current  (void)
341 {
342   GSList *l;
343
344   l = g_static_private_get (&current_cancellable);
345   if (l == NULL)
346     return NULL;
347
348   return G_CANCELLABLE (l->data);
349 }
350
351 /**
352  * g_cancellable_reset:
353  * @cancellable: a #GCancellable object.
354  * 
355  * Resets @cancellable to its uncancelled state. 
356  **/
357 void 
358 g_cancellable_reset (GCancellable *cancellable)
359 {
360   GCancellablePrivate *priv;
361
362   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
363
364   G_LOCK(cancellable);
365
366   priv = cancellable->priv;
367   
368   while (priv->cancelled_running)
369     {
370       priv->cancelled_running_waiting = TRUE;
371       g_cond_wait (cancellable_cond,
372                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
373     }
374   
375   if (priv->cancelled)
376     {
377     /* Make sure we're not leaving old cancel state around */
378       
379 #ifdef G_OS_WIN32
380       if (priv->event)
381         ResetEvent (priv->event);
382 #endif
383       if (priv->cancel_pipe[0] != -1)
384         {
385           gssize c;
386           char ch;
387
388           do
389             c = read (priv->cancel_pipe[0], &ch, 1);
390           while (c == -1 && errno == EINTR);
391         }
392
393       priv->cancelled = FALSE;
394     }
395   G_UNLOCK(cancellable);
396 }
397
398 /**
399  * g_cancellable_is_cancelled:
400  * @cancellable: a #GCancellable or NULL.
401  * 
402  * Checks if a cancellable job has been cancelled.
403  * 
404  * Returns: %TRUE if @cancellable is cancelled, 
405  * FALSE if called with %NULL or if item is not cancelled. 
406  **/
407 gboolean
408 g_cancellable_is_cancelled (GCancellable *cancellable)
409 {
410   return cancellable != NULL && cancellable->priv->cancelled;
411 }
412
413 /**
414  * g_cancellable_set_error_if_cancelled:
415  * @cancellable: a #GCancellable object.
416  * @error: #GError to append error state to.
417  * 
418  * If the @cancellable is cancelled, sets the error to notify
419  * that the operation was cancelled.
420  * 
421  * Returns: %TRUE if @cancellable was cancelled, %FALSE if it was not.
422  **/
423 gboolean
424 g_cancellable_set_error_if_cancelled (GCancellable  *cancellable,
425                                       GError       **error)
426 {
427   if (g_cancellable_is_cancelled (cancellable))
428     {
429       g_set_error_literal (error,
430                            G_IO_ERROR,
431                            G_IO_ERROR_CANCELLED,
432                            _("Operation was cancelled"));
433       return TRUE;
434     }
435   
436   return FALSE;
437 }
438
439 /**
440  * g_cancellable_get_fd:
441  * @cancellable: a #GCancellable.
442  * 
443  * Gets the file descriptor for a cancellable job. This can be used to
444  * implement cancellable operations on Unix systems. The returned fd will
445  * turn readable when @cancellable is cancelled.
446  *
447  * You are not supposed to read from the fd yourself, just check for
448  * readable status. Reading to unset the readable status is done
449  * with g_cancellable_reset().
450  * 
451  * After a successful return from this function, you should use 
452  * g_cancellable_release_fd() to free up resources allocated for 
453  * the returned file descriptor.
454  *
455  * See also g_cancellable_make_pollfd().
456  *
457  * Returns: A valid file descriptor. %-1 if the file descriptor 
458  * is not supported, or on errors. 
459  **/
460 int
461 g_cancellable_get_fd (GCancellable *cancellable)
462 {
463   GCancellablePrivate *priv;
464   int fd;
465
466   if (cancellable == NULL)
467     return -1;
468
469   priv = cancellable->priv;
470
471 #ifdef G_OS_WIN32
472   return -1;
473 #else
474   G_LOCK(cancellable);
475   if (priv->cancel_pipe[0] == -1)
476     g_cancellable_open_pipe (cancellable);
477   fd = priv->cancel_pipe[0];
478   if (fd != -1)
479     priv->fd_refcount++;
480   G_UNLOCK(cancellable);
481 #endif
482
483   return fd;
484 }
485
486 /**
487  * g_cancellable_make_pollfd:
488  * @cancellable: a #GCancellable or %NULL
489  * @pollfd: a pointer to a #GPollFD
490  * 
491  * Creates a #GPollFD corresponding to @cancellable; this can be passed
492  * to g_poll() and used to poll for cancellation. This is useful both
493  * for unix systems without a native poll and for portability to
494  * windows.
495  *
496  * When this function returns %TRUE, you should use 
497  * g_cancellable_release_fd() to free up resources allocated for the 
498  * @pollfd. After a %FALSE return, do not call g_cancellable_release_fd().
499  *
500  * If this function returns %FALSE, either no @cancellable was given or
501  * resource limits prevent this function from allocating the necessary 
502  * structures for polling. (On Linux, you will likely have reached 
503  * the maximum number of file descriptors.) The suggested way to handle
504  * these cases is to ignore the @cancellable.
505  *
506  * You are not supposed to read from the fd yourself, just check for
507  * readable status. Reading to unset the readable status is done
508  * with g_cancellable_reset().
509  *
510  * Returns: %TRUE if @pollfd was successfully initialized, %FALSE on 
511  *          failure to prepare the cancellable.
512  * 
513  * Since: 2.22
514  **/
515 gboolean
516 g_cancellable_make_pollfd (GCancellable *cancellable, GPollFD *pollfd)
517 {
518   g_return_val_if_fail (pollfd != NULL, FALSE);
519   if (cancellable == NULL)
520     return FALSE;
521   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), FALSE);
522
523   {
524 #ifdef G_OS_WIN32
525     GCancellablePrivate *priv;
526
527     priv = cancellable->priv;
528     G_LOCK(cancellable);
529     if (priv->event == NULL)
530       {
531         /* A manual reset anonymous event, starting unset */
532         priv->event = CreateEvent (NULL, TRUE, FALSE, NULL);
533         if (priv->event == NULL)
534           {
535             G_UNLOCK(cancellable);
536             return FALSE;
537           }
538         if (priv->cancelled)
539           SetEvent(priv->event);
540       }
541     priv->fd_refcount++;
542     G_UNLOCK(cancellable);
543
544     pollfd->fd = (gintptr)priv->event;
545 #else /* !G_OS_WIN32 */
546     int fd = g_cancellable_get_fd (cancellable);
547
548     if (fd == -1)
549       return FALSE;
550     pollfd->fd = fd;
551 #endif /* G_OS_WIN32 */
552   }
553
554   pollfd->events = G_IO_IN;
555   pollfd->revents = 0;
556
557   return TRUE;
558 }
559
560 /**
561  * g_cancellable_release_fd:
562  * @cancellable: a #GCancellable
563  *
564  * Releases a resources previously allocated by g_cancellable_get_fd()
565  * or g_cancellable_make_pollfd().
566  *
567  * For compatibility reasons with older releases, calling this function 
568  * is not strictly required, the resources will be automatically freed
569  * when the @cancellable is finalized. However, the @cancellable will
570  * block scarce file descriptors until it is finalized if this function
571  * is not called. This can cause the application to run out of file 
572  * descriptors when many #GCancellables are used at the same time.
573  * 
574  * Since: 2.22
575  **/
576 void
577 g_cancellable_release_fd (GCancellable *cancellable)
578 {
579   GCancellablePrivate *priv;
580
581   if (cancellable == NULL)
582     return;
583
584   g_return_if_fail (G_IS_CANCELLABLE (cancellable));
585   g_return_if_fail (cancellable->priv->fd_refcount > 0);
586
587   priv = cancellable->priv;
588
589   G_LOCK (cancellable);
590   priv->fd_refcount--;
591   if (priv->fd_refcount == 0)
592     g_cancellable_close_pipe (cancellable);
593   G_UNLOCK (cancellable);
594 }
595
596 /**
597  * g_cancellable_cancel:
598  * @cancellable: a #GCancellable object.
599  * 
600  * Will set @cancellable to cancelled, and will emit the
601  * #GCancellable::cancelled signal. (However, see the warning about
602  * race conditions in the documentation for that signal if you are
603  * planning to connect to it.)
604  *
605  * This function is thread-safe. In other words, you can safely call
606  * it from a thread other than the one running the operation that was
607  * passed the @cancellable.
608  *
609  * The convention within gio is that cancelling an asynchronous
610  * operation causes it to complete asynchronously. That is, if you
611  * cancel the operation from the same thread in which it is running,
612  * then the operation's #GAsyncReadyCallback will not be invoked until
613  * the application returns to the main loop.
614  **/
615 void
616 g_cancellable_cancel (GCancellable *cancellable)
617 {
618   GCancellablePrivate *priv;
619
620   if (cancellable == NULL ||
621       cancellable->priv->cancelled)
622     return;
623
624   priv = cancellable->priv;
625
626   G_LOCK(cancellable);
627   if (priv->cancelled)
628     {
629       G_UNLOCK (cancellable);
630       return;
631     }
632
633   priv->cancelled = TRUE;
634   priv->cancelled_running = TRUE;
635 #ifdef G_OS_WIN32
636   if (priv->event)
637     SetEvent (priv->event);
638 #endif
639   if (priv->cancel_pipe[1] != -1)
640     {
641       const char ch = 'x';
642       gssize c;
643
644       do
645         c = write (priv->cancel_pipe[1], &ch, 1);
646       while (c == -1 && errno == EINTR);
647     }
648   G_UNLOCK(cancellable);
649
650   g_object_ref (cancellable);
651   g_signal_emit (cancellable, signals[CANCELLED], 0);
652
653   G_LOCK(cancellable);
654
655   priv->cancelled_running = FALSE;
656   if (priv->cancelled_running_waiting)
657     g_cond_broadcast (cancellable_cond);
658   priv->cancelled_running_waiting = FALSE;
659
660   G_UNLOCK(cancellable);
661
662   g_object_unref (cancellable);
663 }
664
665 /**
666  * g_cancellable_connect:
667  * @cancellable: A #GCancellable.
668  * @callback: The #GCallback to connect.
669  * @data: Data to pass to @callback.
670  * @data_destroy_func: Free function for @data or %NULL.
671  *
672  * Convenience function to connect to the #GCancellable::cancelled
673  * signal. Also handles the race condition that may happen
674  * if the cancellable is cancelled right before connecting.
675  *
676  * @callback is called at most once, either directly at the
677  * time of the connect if @cancellable is already cancelled,
678  * or when @cancellable is cancelled in some thread.
679  *
680  * @data_destroy_func will be called when the handler is
681  * disconnected, or immediately if the cancellable is already
682  * cancelled.
683  *
684  * See #GCancellable::cancelled for details on how to use this.
685  *
686  * Returns: The id of the signal handler or 0 if @cancellable has already
687  *          been cancelled.
688  *
689  * Since: 2.22
690  */
691 gulong
692 g_cancellable_connect (GCancellable   *cancellable,
693                        GCallback       callback,
694                        gpointer        data,
695                        GDestroyNotify  data_destroy_func)
696 {
697   gulong id;
698
699   g_return_val_if_fail (G_IS_CANCELLABLE (cancellable), 0);
700
701   G_LOCK (cancellable);
702
703   if (cancellable->priv->cancelled)
704     {
705       void (*_callback) (GCancellable *cancellable,
706                          gpointer      user_data);
707
708       _callback = (void *)callback;
709       id = 0;
710
711       _callback (cancellable, data);
712
713       if (data_destroy_func)
714         data_destroy_func (data);
715     }
716   else
717     {
718       id = g_signal_connect_data (cancellable, "cancelled",
719                                   callback, data,
720                                   (GClosureNotify) data_destroy_func,
721                                   0);
722     }
723   G_UNLOCK (cancellable);
724
725   return id;
726 }
727
728 /**
729  * g_cancellable_disconnect:
730  * @cancellable: A #GCancellable or %NULL.
731  * @handler_id: Handler id of the handler to be disconnected, or %0.
732  *
733  * Disconnects a handler from a cancellable instance similar to
734  * g_signal_handler_disconnect().  Additionally, in the event that a
735  * signal handler is currently running, this call will block until the
736  * handler has finished.  Calling this function from a
737  * #GCancellable::cancelled signal handler will therefore result in a
738  * deadlock.
739  *
740  * This avoids a race condition where a thread cancels at the
741  * same time as the cancellable operation is finished and the
742  * signal handler is removed. See #GCancellable::cancelled for
743  * details on how to use this.
744  *
745  * If @cancellable is %NULL or @handler_id is %0 this function does
746  * nothing.
747  *
748  * Since: 2.22
749  */
750 void
751 g_cancellable_disconnect (GCancellable  *cancellable,
752                           gulong         handler_id)
753 {
754   GCancellablePrivate *priv;
755
756   if (handler_id == 0 ||  cancellable == NULL)
757     return;
758
759   G_LOCK (cancellable);
760
761   priv = cancellable->priv;
762
763   while (priv->cancelled_running)
764     {
765       priv->cancelled_running_waiting = TRUE;
766       g_cond_wait (cancellable_cond,
767                    g_static_mutex_get_mutex (& G_LOCK_NAME (cancellable)));
768     }
769
770   g_signal_handler_disconnect (cancellable, handler_id);
771   G_UNLOCK (cancellable);
772 }