Imported Upstream version 2.67.1
[platform/upstream/glib.git] / gio / gdbusnamewatching.c
index 2fd0347..8d24700 100644 (file)
@@ -5,7 +5,7 @@
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * version 2.1 of the License, or (at your option) any later version.
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -13,9 +13,7 @@
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General
- * Public License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
- * Boston, MA 02111-1307, USA.
+ * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
  *
  * Author: David Zeuthen <davidz@redhat.com>
  */
@@ -41,7 +39,8 @@
  *
  * Convenience API for watching bus names.
  *
- * <example id="gdbus-watching-names"><title>Simple application watching a name</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-watch-name.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
+ * A simple example for watching a name can be found in
+ * [gdbus-example-watch-name.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-watch-name.c)
  */
 
 G_LOCK_DEFINE_STATIC (lock);
@@ -57,7 +56,7 @@ typedef enum
 
 typedef struct
 {
-  volatile gint             ref_count;
+  gint                      ref_count;  /* (atomic) */
   guint                     id;
   gchar                    *name;
   GBusNameWatcherFlags      flags;
@@ -78,7 +77,10 @@ typedef struct
   gboolean                  initialized;
 } Client;
 
-static guint next_global_id = 1;
+/* Must be accessed atomically. */
+static guint next_global_id = 1;  /* (atomic) */
+
+/* Must be accessed with @lock held. */
 static GHashTable *map_id_to_client = NULL;
 
 static Client *
@@ -103,8 +105,7 @@ client_unref (Client *client)
         }
       g_free (client->name);
       g_free (client->name_owner);
-      if (client->main_context != NULL)
-        g_main_context_unref (client->main_context);
+      g_main_context_unref (client->main_context);
       if (client->user_data_free_func != NULL)
         client->user_data_free_func (client->user_data);
       g_free (client);
@@ -147,6 +148,11 @@ call_handler_data_free (CallHandlerData *data)
 static void
 actually_do_call (Client *client, GDBusConnection *connection, const gchar *name_owner, CallType call_type)
 {
+  /* The client might have been cancelled (g_bus_unwatch_name()) while we were
+   * sitting in the #GMainContext dispatch queue. */
+  if (client->cancelled)
+    return;
+
   switch (call_type)
     {
     case CALL_TYPE_NAME_APPEARED:
@@ -200,6 +206,7 @@ schedule_call_in_idle (Client *client, CallType call_type)
                          call_in_idle_cb,
                          data,
                          (GDestroyNotify) call_handler_data_free);
+  g_source_set_name (idle_source, "[gio, gdbusnamewatching.c] call_in_idle_cb");
   g_source_attach (idle_source, client->main_context);
   g_source_unref (idle_source);
 }
@@ -207,11 +214,15 @@ schedule_call_in_idle (Client *client, CallType call_type)
 static void
 do_call (Client *client, CallType call_type)
 {
+  GMainContext *current_context;
+
   /* only schedule in idle if we're not in the right thread */
-  if (g_main_context_get_thread_default () != client->main_context)
+  current_context = g_main_context_ref_thread_default ();
+  if (current_context != client->main_context)
     schedule_call_in_idle (client, call_type);
   else
     actually_do_call (client, client->connection, client->name_owner, call_type);
+  g_main_context_unref (current_context);
 }
 
 static void
@@ -228,13 +239,12 @@ call_appeared_handler (Client *client)
 }
 
 static void
-call_vanished_handler (Client  *client,
-                       gboolean ignore_cancelled)
+call_vanished_handler (Client *client)
 {
   if (client->previous_call != PREVIOUS_CALL_VANISHED)
     {
       client->previous_call = PREVIOUS_CALL_VANISHED;
-      if (((!client->cancelled) || ignore_cancelled) && client->name_vanished_handler != NULL)
+      if (!client->cancelled && client->name_vanished_handler != NULL)
         {
           do_call (client, CALL_TYPE_NAME_VANISHED);
         }
@@ -243,13 +253,43 @@ call_vanished_handler (Client  *client,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Return a reference to the #Client for @watcher_id, or %NULL if it’s been
+ * unwatched. This is safe to call from any thread. */
+static Client *
+dup_client (guint watcher_id)
+{
+  Client *client;
+
+  G_LOCK (lock);
+
+  g_assert (watcher_id != 0);
+  g_assert (map_id_to_client != NULL);
+
+  client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (watcher_id));
+
+  if (client != NULL)
+    client_ref (client);
+
+  G_UNLOCK (lock);
+
+  return client;
+}
+
+/* Could be called from any thread, so it could be called after client_unref()
+ * has started finalising the #Client. Avoid that by looking up the #Client
+ * atomically. */
 static void
 on_connection_disconnected (GDBusConnection *connection,
                             gboolean         remote_peer_vanished,
                             GError          *error,
                             gpointer         user_data)
 {
-  Client *client = user_data;
+  guint watcher_id = GPOINTER_TO_UINT (user_data);
+  Client *client = NULL;
+
+  client = dup_client (watcher_id);
+  if (client == NULL)
+    return;
 
   if (client->name_owner_changed_subscription_id > 0)
     g_dbus_connection_signal_unsubscribe (client->connection, client->name_owner_changed_subscription_id);
@@ -260,11 +300,14 @@ on_connection_disconnected (GDBusConnection *connection,
   client->name_owner_changed_subscription_id = 0;
   client->connection = NULL;
 
-  call_vanished_handler (client, FALSE);
+  call_vanished_handler (client);
+
+  client_unref (client);
 }
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Will always be called from the thread which acquired client->main_context. */
 static void
 on_name_owner_changed (GDBusConnection *connection,
                        const gchar      *sender_name,
@@ -274,11 +317,16 @@ on_name_owner_changed (GDBusConnection *connection,
                        GVariant         *parameters,
                        gpointer          user_data)
 {
-  Client *client = user_data;
+  guint watcher_id = GPOINTER_TO_UINT (user_data);
+  Client *client = NULL;
   const gchar *name;
   const gchar *old_owner;
   const gchar *new_owner;
 
+  client = dup_client (watcher_id);
+  if (client == NULL)
+    return;
+
   if (!client->initialized)
     goto out;
 
@@ -301,7 +349,7 @@ on_name_owner_changed (GDBusConnection *connection,
     {
       g_free (client->name_owner);
       client->name_owner = NULL;
-      call_vanished_handler (client, FALSE);
+      call_vanished_handler (client);
     }
 
   if (new_owner != NULL && strlen (new_owner) > 0)
@@ -313,7 +361,7 @@ on_name_owner_changed (GDBusConnection *connection,
     }
 
  out:
-  ;
+  client_unref (client);
 }
 
 /* ---------------------------------------------------------------------------------------------------- */
@@ -346,7 +394,7 @@ get_name_owner_cb (GObject      *source_object,
     }
   else
     {
-      call_vanished_handler (client, FALSE);
+      call_vanished_handler (client);
     }
 
   client->initialized = TRUE;
@@ -406,7 +454,7 @@ start_service_by_name_cb (GObject      *source_object,
       else
         {
           g_warning ("Unexpected reply %d from StartServiceByName() method", start_service_result);
-          call_vanished_handler (client, FALSE);
+          call_vanished_handler (client);
           client->initialized = TRUE;
         }
     }
@@ -438,7 +486,7 @@ has_connection (Client *client)
   client->disconnected_signal_handler_id = g_signal_connect (client->connection,
                                                              "closed",
                                                              G_CALLBACK (on_connection_disconnected),
-                                                             client);
+                                                             GUINT_TO_POINTER (client->id));
 
   /* start listening to NameOwnerChanged messages immediately */
   client->name_owner_changed_subscription_id = g_dbus_connection_signal_subscribe (client->connection,
@@ -449,7 +497,7 @@ has_connection (Client *client)
                                                                                    client->name,
                                                                                    G_DBUS_SIGNAL_FLAGS_NONE,
                                                                                    on_name_owner_changed,
-                                                                                   client,
+                                                                                   GUINT_TO_POINTER (client->id),
                                                                                    NULL);
 
   if (client->flags & G_BUS_NAME_WATCHER_FLAGS_AUTO_START)
@@ -485,7 +533,7 @@ connection_get_cb (GObject      *source_object,
   client->connection = g_bus_get_finish (res, NULL);
   if (client->connection == NULL)
     {
-      call_vanished_handler (client, FALSE);
+      call_vanished_handler (client);
       goto out;
     }
 
@@ -502,17 +550,17 @@ connection_get_cb (GObject      *source_object,
  * @bus_type: The type of bus to watch a name on.
  * @name: The name (well-known or unique) to watch.
  * @flags: Flags from the #GBusNameWatcherFlags enumeration.
- * @name_appeared_handler: Handler to invoke when @name is known to exist or %NULL.
- * @name_vanished_handler: Handler to invoke when @name is known to not exist or %NULL.
+ * @name_appeared_handler: (nullable): Handler to invoke when @name is known to exist or %NULL.
+ * @name_vanished_handler: (nullable): Handler to invoke when @name is known to not exist or %NULL.
  * @user_data: User data to pass to handlers.
- * @user_data_free_func: Function for freeing @user_data or %NULL.
+ * @user_data_free_func: (nullable): Function for freeing @user_data or %NULL.
  *
  * Starts watching @name on the bus specified by @bus_type and calls
  * @name_appeared_handler and @name_vanished_handler when the name is
- * known to have a owner respectively known to lose its
- * owner. Callbacks will be invoked in the <link
- * linkend="g-main-context-push-thread-default">thread-default main
- * loop</link> of the thread you are calling this function from.
+ * known to have an owner respectively known to lose its
+ * owner. Callbacks will be invoked in the
+ * [thread-default main context][g-main-context-push-thread-default]
+ * of the thread you are calling this function from.
  *
  * You are guaranteed that one of the handlers will be invoked after
  * calling this function. When you are done watching the name, just
@@ -531,13 +579,13 @@ connection_get_cb (GObject      *source_object,
  * guaranteed that the next time one of the handlers is invoked, it
  * will be @name_vanished_handler. The reverse is also true.
  *
- * This behavior makes it very simple to write applications that wants
- * to take action when a certain name exists, see <xref
- * linkend="gdbus-watching-names"/>. Basically, the application
- * should create object proxies in @name_appeared_handler and destroy
- * them again (if any) in @name_vanished_handler.
+ * This behavior makes it very simple to write applications that want
+ * to take action when a certain [name exists][gdbus-watching-names].
+ * Basically, the application should create object proxies in
+ * @name_appeared_handler and destroy them again (if any) in
+ * @name_vanished_handler.
  *
- * Returns: An identifier (never 0) that an be used with
+ * Returns: An identifier (never 0) that can be used with
  * g_bus_unwatch_name() to stop watching the name.
  *
  * Since: 2.26
@@ -559,16 +607,14 @@ g_bus_watch_name (GBusType                  bus_type,
 
   client = g_new0 (Client, 1);
   client->ref_count = 1;
-  client->id = next_global_id++; /* TODO: uh oh, handle overflow */
+  client->id = (guint) g_atomic_int_add (&next_global_id, 1); /* TODO: uh oh, handle overflow */
   client->name = g_strdup (name);
   client->flags = flags;
   client->name_appeared_handler = name_appeared_handler;
   client->name_vanished_handler = name_vanished_handler;
   client->user_data = user_data;
   client->user_data_free_func = user_data_free_func;
-  client->main_context = g_main_context_get_thread_default ();
-  if (client->main_context != NULL)
-    g_main_context_ref (client->main_context);
+  client->main_context = g_main_context_ref_thread_default ();
 
   if (map_id_to_client == NULL)
     {
@@ -593,15 +639,15 @@ g_bus_watch_name (GBusType                  bus_type,
  * @connection: A #GDBusConnection.
  * @name: The name (well-known or unique) to watch.
  * @flags: Flags from the #GBusNameWatcherFlags enumeration.
- * @name_appeared_handler: Handler to invoke when @name is known to exist or %NULL.
- * @name_vanished_handler: Handler to invoke when @name is known to not exist or %NULL.
+ * @name_appeared_handler: (nullable): Handler to invoke when @name is known to exist or %NULL.
+ * @name_vanished_handler: (nullable): Handler to invoke when @name is known to not exist or %NULL.
  * @user_data: User data to pass to handlers.
- * @user_data_free_func: Function for freeing @user_data or %NULL.
+ * @user_data_free_func: (nullable): Function for freeing @user_data or %NULL.
  *
  * Like g_bus_watch_name() but takes a #GDBusConnection instead of a
  * #GBusType.
  *
- * Returns: An identifier (never 0) that an be used with
+ * Returns: An identifier (never 0) that can be used with
  * g_bus_unwatch_name() to stop watching the name.
  *
  * Since: 2.26
@@ -623,16 +669,14 @@ guint g_bus_watch_name_on_connection (GDBusConnection          *connection,
 
   client = g_new0 (Client, 1);
   client->ref_count = 1;
-  client->id = next_global_id++; /* TODO: uh oh, handle overflow */
+  client->id = (guint) g_atomic_int_add (&next_global_id, 1); /* TODO: uh oh, handle overflow */
   client->name = g_strdup (name);
   client->flags = flags;
   client->name_appeared_handler = name_appeared_handler;
   client->name_vanished_handler = name_vanished_handler;
   client->user_data = user_data;
   client->user_data_free_func = user_data_free_func;
-  client->main_context = g_main_context_get_thread_default ();
-  if (client->main_context != NULL)
-    g_main_context_ref (client->main_context);
+  client->main_context = g_main_context_ref_thread_default ();
 
   if (map_id_to_client == NULL)
     map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
@@ -688,7 +732,7 @@ watch_with_closures_on_name_appeared (GDBusConnection *connection,
                                       gpointer         user_data)
 {
   WatchNameData *data = user_data;
-  GValue params[3] = { { 0, }, { 0, }, { 0, } };
+  GValue params[3] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
 
   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
   g_value_set_object (&params[0], connection);
@@ -712,7 +756,7 @@ watch_with_closures_on_name_vanished (GDBusConnection *connection,
                                       gpointer         user_data)
 {
   WatchNameData *data = user_data;
-  GValue params[2] = { { 0, }, { 0, } };
+  GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
 
   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
   g_value_set_object (&params[0], connection);
@@ -741,23 +785,21 @@ bus_watch_name_free_func (gpointer user_data)
 }
 
 /**
- * g_bus_watch_name_with_closures:
+ * g_bus_watch_name_with_closures: (rename-to g_bus_watch_name)
  * @bus_type: The type of bus to watch a name on.
  * @name: The name (well-known or unique) to watch.
  * @flags: Flags from the #GBusNameWatcherFlags enumeration.
- * @name_appeared_closure: (allow-none): #GClosure to invoke when @name is known
+ * @name_appeared_closure: (nullable): #GClosure to invoke when @name is known
  * to exist or %NULL.
- * @name_vanished_closure: (allow-none): #GClosure to invoke when @name is known
+ * @name_vanished_closure: (nullable): #GClosure to invoke when @name is known
  * to not exist or %NULL.
  *
  * Version of g_bus_watch_name() using closures instead of callbacks for
  * easier binding in other languages.
  *
- * Returns: An identifier (never 0) that an be used with
+ * Returns: An identifier (never 0) that can be used with
  * g_bus_unwatch_name() to stop watching the name.
  *
- * Rename to: g_bus_watch_name
- *
  * Since: 2.26
  */
 guint
@@ -777,23 +819,21 @@ g_bus_watch_name_with_closures (GBusType                 bus_type,
 }
 
 /**
- * g_bus_watch_name_on_connection_with_closures:
+ * g_bus_watch_name_on_connection_with_closures: (rename-to g_bus_watch_name_on_connection)
  * @connection: A #GDBusConnection.
  * @name: The name (well-known or unique) to watch.
  * @flags: Flags from the #GBusNameWatcherFlags enumeration.
- * @name_appeared_closure: (allow-none): #GClosure to invoke when @name is known
+ * @name_appeared_closure: (nullable): #GClosure to invoke when @name is known
  * to exist or %NULL.
- * @name_vanished_closure: (allow-none): #GClosure to invoke when @name is known
+ * @name_vanished_closure: (nullable): #GClosure to invoke when @name is known
  * to not exist or %NULL.
  *
  * Version of g_bus_watch_name_on_connection() using closures instead of callbacks for
  * easier binding in other languages.
  *
- * Returns: An identifier (never 0) that an be used with
+ * Returns: An identifier (never 0) that can be used with
  * g_bus_unwatch_name() to stop watching the name.
  *
- * Rename to: g_bus_watch_name_on_connection
- *
  * Since: 2.26
  */
 guint g_bus_watch_name_on_connection_with_closures (
@@ -818,6 +858,13 @@ guint g_bus_watch_name_on_connection_with_closures (
  *
  * Stops watching a name.
  *
+ * Note that there may still be D-Bus traffic to process (relating to watching
+ * and unwatching the name) in the current thread-default #GMainContext after
+ * this function has returned. You should continue to iterate the #GMainContext
+ * until the #GDestroyNotify function passed to g_bus_watch_name() is called, in
+ * order to avoid memory leaks through callbacks queued on the #GMainContext
+ * after it’s stopped being iterated.
+ *
  * Since: 2.26
  */
 void