Commit f3375b3945 for qemu.org

commit f3375b3945609cd5b14259ad7d7175b33f853d61
Author: Marc Morcos <marcmorcos@google.com>
Date:   Sat Dec 13 00:14:42 2025 +0000

    qmp: Fix thread race

    This fixes a thread race involving the monitor in monitor_qmp_event and monitor_qapi_event_emit .

    Signed-off-by: Marc Morcos <marcmorcos@google.com>
    Link: https://lore.kernel.org/r/20251213001443.2041258-4-marcmorcos@google.com
    [Use QEMU_LOCK_GUARD and "continue". - Paolo]
    Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>

diff --git a/monitor/monitor.c b/monitor/monitor.c
index c5a5d30877..1273eb7260 100644
--- a/monitor/monitor.c
+++ b/monitor/monitor.c
@@ -346,9 +346,13 @@ static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)
         }

         qmp_mon = container_of(mon, MonitorQMP, common);
-        if (qmp_mon->commands != &qmp_cap_negotiation_commands) {
-            qmp_send_response(qmp_mon, qdict);
+        {
+            QEMU_LOCK_GUARD(&mon->mon_lock);
+            if (qmp_mon->commands == &qmp_cap_negotiation_commands) {
+                continue;
+            }
         }
+        qmp_send_response(qmp_mon, qdict);
     }
 }

diff --git a/monitor/qmp.c b/monitor/qmp.c
index cb99a12d94..e1419a9efa 100644
--- a/monitor/qmp.c
+++ b/monitor/qmp.c
@@ -462,8 +462,10 @@ static void monitor_qmp_event(void *opaque, QEMUChrEvent event)

     switch (event) {
     case CHR_EVENT_OPENED:
-        mon->commands = &qmp_cap_negotiation_commands;
-        monitor_qmp_caps_reset(mon);
+        WITH_QEMU_LOCK_GUARD(&mon->common.mon_lock) {
+            mon->commands = &qmp_cap_negotiation_commands;
+            monitor_qmp_caps_reset(mon);
+        }
         data = qmp_greeting(mon);
         qmp_send_response(mon, data);
         qobject_unref(data);