From 72585ff4f5b94de910b27ff22780aa1736d1770e Mon Sep 17 00:00:00 2001
From: Michal Privoznik <mprivozn@redhat.com>
Date: Wed, 27 Oct 2021 13:38:05 +0200
Subject: [PATCH 103/108] qemu_agent: Rework domain object locking when opening
 agent
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Just like qemuMonitorOpen(), hold the domain object locked
throughout the whole time of qemuConnectAgent() and unlock it
only for a brief time of actual connect() (because this is the
only part that has a potential of blocking).

The reason is that qemuAgentOpen() does access domain object
(well, its privateData) AND also at least one argument (@context)
depends on domain object. Accessing these without the lock is
potentially dangerous.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1845468#c12
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
(cherry picked from commit 108e131a3df529ff4e0f3a33a30b37cea7a62e26)
---
 src/qemu/qemu_agent.c   | 3 +++
 src/qemu/qemu_process.c | 4 ----
 2 files changed, 3 insertions(+), 4 deletions(-)

diff --git a/src/qemu/qemu_agent.c b/src/qemu/qemu_agent.c
index 31d3268d42..1cd745c88e 100644
--- a/src/qemu/qemu_agent.c
+++ b/src/qemu/qemu_agent.c
@@ -709,7 +709,10 @@ qemuAgentOpen(virDomainObjPtr vm,
         goto cleanup;
     }
 
+    virObjectUnlock(vm);
     agent->fd = qemuAgentOpenUnix(config->data.nix.path);
+    virObjectLock(vm);
+
     if (agent->fd == -1)
         goto cleanup;
 
diff --git a/src/qemu/qemu_process.c b/src/qemu/qemu_process.c
index bf5375bcde..360c4fcbb1 100644
--- a/src/qemu/qemu_process.c
+++ b/src/qemu/qemu_process.c
@@ -234,16 +234,12 @@ qemuConnectAgent(virQEMUDriverPtr driver, virDomainObjPtr vm)
      * deleted while the agent is active */
     virObjectRef(vm);
 
-    virObjectUnlock(vm);
-
     agent = qemuAgentOpen(vm,
                           config->source,
                           virEventThreadGetContext(priv->eventThread),
                           &agentCallbacks,
                           virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_VSERPORT_CHANGE));
 
-    virObjectLock(vm);
-
     if (agent == NULL)
         virObjectUnref(vm);
 
-- 
2.33.0

