diff --git a/src/platform/backends/qemu/qemu_virtual_machine.cpp b/src/platform/backends/qemu/qemu_virtual_machine.cpp index 85460594eb..3cbbaa6274 100644 --- a/src/platform/backends/qemu/qemu_virtual_machine.cpp +++ b/src/platform/backends/qemu/qemu_virtual_machine.cpp @@ -295,8 +295,11 @@ void mp::QemuVirtualMachine::shutdown() if (state == State::starting) update_shutdown_status = false; - vm_process->kill(); - vm_process->wait_for_finished(); + if (vm_process) + { + vm_process->kill(); + vm_process->wait_for_finished(); + } } } @@ -390,7 +393,7 @@ void mp::QemuVirtualMachine::on_restart() void mp::QemuVirtualMachine::ensure_vm_is_running() { std::lock_guard lock{state_mutex}; - if (!vm_process->running()) + if (!vm_process || !vm_process->running()) { // Have to set 'off' here so there is an actual state change to compare to for // the cond var's predicate diff --git a/tests/qemu/test_qemu_backend.cpp b/tests/qemu/test_qemu_backend.cpp index df62557c7e..4aa4cceec3 100644 --- a/tests/qemu/test_qemu_backend.cpp +++ b/tests/qemu/test_qemu_backend.cpp @@ -87,6 +87,18 @@ TEST_F(QemuBackend, creates_in_off_state) EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off)); } +TEST_F(QemuBackend, machine_in_off_state_handles_shutdown) +{ + mpt::StubVMStatusMonitor stub_monitor; + mp::QemuVirtualMachineFactory backend{data_dir.path()}; + + auto machine = backend.create_virtual_machine(default_description, stub_monitor); + EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off)); + + machine->shutdown(); + EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off)); +} + TEST_F(QemuBackend, machine_start_shutdown_sends_monitoring_events) { NiceMock mock_monitor;