Skip to content

Commit 1633b37

Browse files
ppennaCopilot
andcommitted
debug_worker: detach the debugger when its session ends
The gdb stub sent DebugRequest::Attach when GDB connected, but never DebugRequest::Detach, whether GDB detached, its connection dropped, or the worker stopped or restarted (microsoft/nvx#2094). The partition went on treating the gone debugger as attached: the session's hardware breakpoints and single-stepping stayed set on the VPs; the halts that followed, a power-off, reset, or triple fault included, went to the debugger instead of the VM's client, so a client set to exit or reset on them never heard of them; and a paused VM that the debugger held stayed held until a new session or a clear-halt. The stub's VM proxy also kept the session's hardware breakpoints, which the next session's first resume set on the VPs again, unknown to its GDB. run_state_machine now attaches through a Session guard of the VM proxy, which sends Detach when it is dropped, so that every end of a session detaches: GDB's D or k packet and a target exit, which reach GdbStubStateMachine::Disconnected; an error, which returns early, as a dropped connection does whether the VM is stopped or running; and the worker dropping the session as it stops or restarts. The guard also clears the proxy's breakpoints, stepping, and stop channel. The Guide's gdbstub page and DebugRequest::Detach say what a detach does; the Guide also says that GDB's software breakpoints, which it writes into guest memory, stay there when it loses its connection while the VM runs. Tests, in the debug worker, which run the stub on a TCP connection, send GDB's packets, and serve the stub's requests as the partition does: - the_debugger_detaches_when_gdb_detaches sends D. - the_debugger_detaches_when_the_connection_drops closes the connection while the VM is stopped, and while it runs after a vCont;c. - the_debugger_detaches_when_the_session_is_dropped drops the session, as the worker does when it stops or restarts. - a_session_does_not_set_the_breakpoints_of_the_previous_one sets a hardware breakpoint with Z1 in a session that then drops, and checks the debug state that the next session's first resume sets. On d44a113, on Windows x64, all four fail, since no Detach ends a session. With the change, they pass, as do the tests of vmm_core and vmm_core_defs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 320e09c commit 1633b37

6 files changed

Lines changed: 253 additions & 11 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1307,6 +1307,7 @@ dependencies = [
13071307
"mesh_worker",
13081308
"pal_async",
13091309
"socket2",
1310+
"test_with_tracing",
13101311
"tracelimit",
13111312
"tracing",
13121313
"vmm_core_defs",

‎Guide/src/reference/dev_feats/gdbstub.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,15 @@ You may find [this blog post](https://blog.mattjustice.com/2018/08/24/gdb-for-wi
119119
useful, as it includes a table of common `gdb` commands along with their WinDbg
120120
counterparts.
121121

122+
Detaching GDB, or losing its connection, ends the debugging session: the
123+
hardware breakpoints and single-stepping that GDB set are cleared, and OpenVMM
124+
handles the VM's halts, such as a guest power-off or reset, which go to the
125+
debugger while one is attached. GDB removes the software breakpoints that it
126+
writes into guest memory when it detaches, but not when it loses its connection
127+
while the VM runs. A VM that the debugger stopped stays halted, and OpenVMM
128+
reports that halt like any other; `clear-halt` in the interactive console
129+
resumes it.
130+
122131
## Connecting via WinDbg
123132

124133
WinDbg doesn't understand the GDB Remote Serial Protocol directly, but

‎vmm_core/vmm_core_defs/src/debug_rpc.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ use virt::x86::SegmentRegister;
1818
pub enum DebugRequest {
1919
/// The debugger has been attached.
2020
Attach,
21-
/// The debugger has been detached.
21+
/// The debugger has been detached, which the debug worker sends when a
22+
/// session ends, however it ends.
2223
///
2324
/// The VM clears the session's debug state, and reports its halts to its
2425
/// client again, starting with a recorded halt that went to the debugger

‎workers/debug_worker/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ socket2.workspace = true
2525
tracing.workspace = true
2626
tracelimit.workspace = true
2727

28+
[dev-dependencies]
29+
test_with_tracing.workspace = true
2830

2931
[lints]
3032
workspace = true

‎workers/debug_worker/src/gdb/mod.rs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ use futures::executor::block_on;
66
use gdbstub::common::Tid;
77
use mesh::rpc::RpcSend;
88
use std::num::NonZeroUsize;
9+
use std::ops::Deref;
10+
use std::ops::DerefMut;
911
use vmm_core_defs::debug_rpc::DebugRequest;
1012
use vmm_core_defs::debug_rpc::DebugStopReason;
1113
use vmm_core_defs::debug_rpc::GuestAddress;
@@ -42,6 +44,13 @@ impl VmProxy {
4244
(self.req_chan, self.vps.len() as u32)
4345
}
4446

47+
/// Attaches the debugger to the VM for a session, which detaches it when
48+
/// dropped.
49+
pub fn attach(&mut self) -> Session<'_> {
50+
self.send_req(DebugRequest::Attach);
51+
Session(self)
52+
}
53+
4554
pub fn send_req(&mut self, req: DebugRequest) {
4655
self.req_chan.send(req);
4756
}
@@ -111,3 +120,35 @@ impl VmProxy {
111120
Ok(())
112121
}
113122
}
123+
124+
/// A debugger session, during which the debugger is attached to the VM.
125+
///
126+
/// Dropping the session detaches the debugger, however the session ends: GDB
127+
/// detaching, its connection dropping, or the worker stopping.
128+
pub struct Session<'a>(&'a mut VmProxy);
129+
130+
impl Drop for Session<'_> {
131+
fn drop(&mut self) {
132+
// The VM clears the session's hardware breakpoints and single-stepping
133+
// when the debugger detaches, so forget them too, lest the next
134+
// session's first resume set them again.
135+
self.0.breakpoints = [None; 4];
136+
self.0.vps.fill(Vp::default());
137+
self.0.stop_chan = None;
138+
self.0.send_req(DebugRequest::Detach);
139+
}
140+
}
141+
142+
impl Deref for Session<'_> {
143+
type Target = VmProxy;
144+
145+
fn deref(&self) -> &VmProxy {
146+
self.0
147+
}
148+
}
149+
150+
impl DerefMut for Session<'_> {
151+
fn deref_mut(&mut self) -> &mut VmProxy {
152+
self.0
153+
}
154+
}

‎workers/debug_worker/src/lib.rs‎

Lines changed: 198 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -207,25 +207,23 @@ where
207207
let state_machine_fut = async {
208208
match architecture {
209209
Architecture::X86_64 => {
210-
run_state_machine(
210+
run_state_machine::<gdb::arch::x86::X86_64_QEMU>(
211211
socket,
212-
VmTarget::<gdb::arch::x86::X86_64_QEMU>::new(&mut vm_proxy),
212+
&mut vm_proxy,
213213
)
214214
.await
215215
}
216216
Architecture::I8086 => {
217-
run_state_machine(
217+
run_state_machine::<gdb::arch::x86::I8086>(
218218
socket,
219-
VmTarget::<gdb::arch::x86::I8086>::new(&mut vm_proxy),
219+
&mut vm_proxy,
220220
)
221221
.await
222222
}
223223
Architecture::Aarch64 => {
224-
run_state_machine(
224+
run_state_machine::<gdbstub_arch::aarch64::AArch64>(
225225
socket,
226-
VmTarget::<gdbstub_arch::aarch64::AArch64>::new(
227-
&mut vm_proxy,
228-
),
226+
&mut vm_proxy,
229227
)
230228
.await
231229
}
@@ -272,15 +270,17 @@ where
272270

273271
async fn run_state_machine<T: TargetArch>(
274272
socket: PolledSocket<Socket>,
275-
mut vm_target: VmTarget<'_, T>,
273+
vm_proxy: &mut VmProxy,
276274
) -> Result<(), gdbstub::stub::GdbStubError<anyhow::Error, std::io::Error>> {
277275
use gdbstub::common::Signal;
278276
use gdbstub::stub::DisconnectReason;
279277
use gdbstub::stub::GdbStubError;
280278
use gdbstub::stub::MultiThreadStopReason;
281279
use gdbstub::stub::state_machine::GdbStubStateMachine;
282280

283-
vm_target.send_req(DebugRequest::Attach);
281+
// Dropping the session detaches the debugger, however the session ends.
282+
let mut session = vm_proxy.attach();
283+
let mut vm_target = VmTarget::<T>::new(&mut session);
284284
let (init_break_send, init_break_recv) = mesh::oneshot();
285285
vm_target.send_req(DebugRequest::Resume {
286286
response: init_break_send,
@@ -463,3 +463,191 @@ impl gdbstub::conn::Connection for SocketConnection {
463463
self.0.get_mut().flush()
464464
}
465465
}
466+
467+
#[cfg(test)]
468+
mod tests {
469+
use super::run_state_machine;
470+
use crate::gdb::VmProxy;
471+
use crate::gdb::arch::x86::X86_64_QEMU;
472+
use futures::AsyncReadExt;
473+
use futures::AsyncWriteExt;
474+
use futures::future::Either;
475+
use gdbstub::stub::GdbStubError;
476+
use pal_async::DefaultDriver;
477+
use pal_async::async_test;
478+
use pal_async::socket::PolledSocket;
479+
use socket2::Socket;
480+
use std::net::TcpListener;
481+
use std::net::TcpStream;
482+
use test_with_tracing::test;
483+
use vmm_core_defs::debug_rpc::DebugRequest;
484+
use vmm_core_defs::debug_rpc::DebugStopReason;
485+
486+
type SessionResult = Result<(), GdbStubError<anyhow::Error, std::io::Error>>;
487+
488+
/// Returns a VM proxy for one VP, and the receiver of its requests.
489+
fn vm() -> (VmProxy, mesh::Receiver<DebugRequest>) {
490+
let (send, recv) = mesh::channel();
491+
(VmProxy::new(send, 1), recv)
492+
}
493+
494+
/// Returns both ends of a connection to the stub: GDB's, and the stub's.
495+
fn connect(driver: &DefaultDriver) -> (PolledSocket<Socket>, PolledSocket<Socket>) {
496+
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
497+
let gdb = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
498+
let (stub, _) = listener.accept().unwrap();
499+
(
500+
PolledSocket::new(driver, Socket::from(gdb)).unwrap(),
501+
PolledSocket::new(driver, Socket::from(stub)).unwrap(),
502+
)
503+
}
504+
505+
/// Runs a debugger session on `stub` against `vm`.
506+
async fn session(stub: PolledSocket<Socket>, vm: &mut VmProxy) -> SessionResult {
507+
run_state_machine::<X86_64_QEMU>(stub, vm).await
508+
}
509+
510+
/// Sends `data` to the stub as a GDB packet.
511+
async fn send(gdb: &mut PolledSocket<Socket>, data: &str) {
512+
let checksum = data.bytes().fold(0u8, |sum, byte| sum.wrapping_add(byte));
513+
gdb.write_all(format!("${data}#{checksum:02x}").as_bytes())
514+
.await
515+
.unwrap();
516+
}
517+
518+
/// Returns the data of the next packet that the stub sends to GDB.
519+
async fn receive(gdb: &mut PolledSocket<Socket>) -> String {
520+
let mut byte = [0];
521+
// Skip the stub's acknowledgements of GDB's packets.
522+
while byte != *b"$" {
523+
gdb.read_exact(&mut byte).await.unwrap();
524+
}
525+
let mut data = Vec::new();
526+
loop {
527+
gdb.read_exact(&mut byte).await.unwrap();
528+
if byte == *b"#" {
529+
break;
530+
}
531+
data.push(byte[0]);
532+
}
533+
gdb.read_exact(&mut [0; 2]).await.unwrap();
534+
String::from_utf8(data).unwrap()
535+
}
536+
537+
/// Serves the requests with which the stub attaches, as a running VM does,
538+
/// which the stub's break stops.
539+
async fn attach(requests: &mut mesh::Receiver<DebugRequest>) {
540+
assert!(matches!(
541+
requests.recv().await.unwrap(),
542+
DebugRequest::Attach
543+
));
544+
let DebugRequest::Resume { response } = requests.recv().await.unwrap() else {
545+
panic!("expected a resume");
546+
};
547+
assert!(matches!(
548+
requests.recv().await.unwrap(),
549+
DebugRequest::Break
550+
));
551+
response.send(DebugStopReason::Break);
552+
}
553+
554+
/// Asserts that the stub detached the debugger from the VM, and requested
555+
/// nothing more.
556+
fn assert_detached(requests: &mut mesh::Receiver<DebugRequest>) {
557+
assert!(matches!(requests.try_recv().unwrap(), DebugRequest::Detach));
558+
assert!(requests.try_recv().is_err());
559+
}
560+
561+
#[async_test]
562+
async fn the_debugger_detaches_when_gdb_detaches(driver: DefaultDriver) {
563+
let (mut vm, mut requests) = vm();
564+
let (mut gdb, stub) = connect(&driver);
565+
let client = async {
566+
attach(&mut requests).await;
567+
send(&mut gdb, "D").await;
568+
assert_eq!(receive(&mut gdb).await, "OK");
569+
};
570+
let (result, ()) = futures::join!(session(stub, &mut vm), client);
571+
result.unwrap();
572+
assert_detached(&mut requests);
573+
}
574+
575+
#[async_test]
576+
async fn the_debugger_detaches_when_the_connection_drops(driver: DefaultDriver) {
577+
for running in [false, true] {
578+
let (mut vm, mut requests) = vm();
579+
let (mut gdb, stub) = connect(&driver);
580+
let client = async {
581+
attach(&mut requests).await;
582+
let mut resume = None;
583+
if running {
584+
// GDB continues the VM, and goes away while it runs.
585+
send(&mut gdb, "vCont;c").await;
586+
assert!(matches!(
587+
requests.recv().await.unwrap(),
588+
DebugRequest::SetDebugState { vp: 0, .. }
589+
));
590+
resume = Some(requests.recv().await.unwrap());
591+
assert!(matches!(resume, Some(DebugRequest::Resume { .. })));
592+
}
593+
drop(gdb);
594+
resume
595+
};
596+
let (result, _resume) = futures::join!(session(stub, &mut vm), client);
597+
assert!(result.is_err());
598+
assert_detached(&mut requests);
599+
}
600+
}
601+
602+
#[async_test]
603+
async fn the_debugger_detaches_when_the_session_is_dropped(driver: DefaultDriver) {
604+
let (mut vm, mut requests) = vm();
605+
let (_gdb, stub) = connect(&driver);
606+
{
607+
let session = Box::pin(session(stub, &mut vm));
608+
let client = Box::pin(attach(&mut requests));
609+
let Either::Right(((), session)) = futures::future::select(session, client).await
610+
else {
611+
panic!("the session ended");
612+
};
613+
// The worker drops a session when it stops or restarts.
614+
drop(session);
615+
}
616+
assert_detached(&mut requests);
617+
}
618+
619+
#[async_test]
620+
async fn a_session_does_not_set_the_breakpoints_of_the_previous_one(driver: DefaultDriver) {
621+
let (mut vm, mut requests) = vm();
622+
623+
// GDB sets a hardware breakpoint, and goes away.
624+
let (mut gdb, stub) = connect(&driver);
625+
let client = async {
626+
attach(&mut requests).await;
627+
send(&mut gdb, "Z1,1000,1").await;
628+
assert_eq!(receive(&mut gdb).await, "OK");
629+
drop(gdb);
630+
};
631+
let (result, ()) = futures::join!(session(stub, &mut vm), client);
632+
assert!(result.is_err());
633+
assert_detached(&mut requests);
634+
635+
// The next session's first resume sets no breakpoint.
636+
let (mut gdb, stub) = connect(&driver);
637+
let client = async {
638+
attach(&mut requests).await;
639+
send(&mut gdb, "vCont;c").await;
640+
let DebugRequest::SetDebugState { vp: 0, state } = requests.recv().await.unwrap()
641+
else {
642+
panic!("expected the debug state of VP 0");
643+
};
644+
assert_eq!(state.breakpoints, [None; 4]);
645+
let resume = requests.recv().await.unwrap();
646+
drop(gdb);
647+
resume
648+
};
649+
let (result, _resume) = futures::join!(session(stub, &mut vm), client);
650+
assert!(result.is_err());
651+
assert_detached(&mut requests);
652+
}
653+
}

0 commit comments

Comments
 (0)