From eb33af53e004ef63539a48f074987b700149fc41 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 12 Mar 2023 10:37:47 +0800 Subject: [PATCH] kernel: gdb: break features into individual files Since gdbstub is able to do this, break individual features into their own files. Signed-off-by: Sean Cross --- kernel/src/debug/gdb.rs | 586 +----------------- kernel/src/debug/gdb/breakpoints.rs | 29 + kernel/src/debug/gdb/extended_mode.rs | 72 +++ kernel/src/debug/gdb/monitor.rs | 75 +++ kernel/src/debug/gdb/multi_thread_base.rs | 208 +++++++ kernel/src/debug/gdb/multi_thread_resume.rs | 47 ++ kernel/src/debug/gdb/riscv.rs | 0 .../src/debug/gdb/single_register_access.rs | 125 ++++ kernel/src/debug/gdb/target.rs | 34 + 9 files changed, 605 insertions(+), 571 deletions(-) create mode 100644 kernel/src/debug/gdb/breakpoints.rs create mode 100644 kernel/src/debug/gdb/extended_mode.rs create mode 100644 kernel/src/debug/gdb/monitor.rs create mode 100644 kernel/src/debug/gdb/multi_thread_base.rs create mode 100644 kernel/src/debug/gdb/multi_thread_resume.rs create mode 100644 kernel/src/debug/gdb/riscv.rs create mode 100644 kernel/src/debug/gdb/single_register_access.rs create mode 100644 kernel/src/debug/gdb/target.rs diff --git a/kernel/src/debug/gdb.rs b/kernel/src/debug/gdb.rs index 68a7dea53..5113aff40 100644 --- a/kernel/src/debug/gdb.rs +++ b/kernel/src/debug/gdb.rs @@ -1,28 +1,28 @@ -use gdbstub::common::{Signal, Tid}; +use gdbstub::common::Signal; use gdbstub::conn::Connection; use gdbstub::stub::state_machine::GdbStubStateMachine; use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason}; -use gdbstub::target; -use gdbstub::target::ext::base::multithread::{MultiThreadBase, MultiThreadResume}; -use gdbstub::target::ext::base::single_register_access::{ - SingleRegisterAccess, SingleRegisterAccessOps, -}; -use gdbstub::target::ext::base::BaseOps; -use gdbstub::target::ext::extended_mode::{AttachKind, ShouldTerminate}; -use gdbstub::target::ext::monitor_cmd::MonitorCmd; -use gdbstub::target::{Target, TargetError, TargetResult}; -use gdbstub_arch::riscv::reg::id::RiscvRegId; +use gdbstub::target::Target; use crate::io::SerialRead; use crate::platform::precursor::gdbuart::GdbUart; -use core::convert::TryInto; -// use core::num::{NonZeroU16, NonZeroUsize}; +mod breakpoints; +mod extended_mode; +mod monitor; +mod multi_thread_base; +mod multi_thread_resume; +mod single_register_access; +mod target; pub struct XousTarget { pid: Option, - // breakpoints: [Option<(NonZeroUsize, NonZeroU16)>; 16], + + /// When doing a `stepi` we patch the instruction with an illegal instruction + /// and store the previous value here. + patched_instruction: usize, } + pub struct XousDebugState<'a> { pub target: XousTarget, pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>, @@ -58,567 +58,11 @@ impl XousTarget { pub fn new() -> XousTarget { XousTarget { pid: None, - // breakpoints: [None; 16], + patched_instruction: 0, } } } -impl Target for XousTarget { - type Arch = gdbstub_arch::riscv::Riscv32; - type Error = &'static str; - - fn base_ops(&mut self) -> BaseOps { - BaseOps::MultiThread(self) - } - - fn support_breakpoints( - &mut self, - ) -> Option> { - Some(self) - } - - /// Opt in to having GDB handle breakpoints for us. This allows for an unlimited number - /// of breakpoints without having us keep track of the breakpoints ourselves. - fn guard_rail_implicit_sw_breakpoints(&self) -> bool { - true - } - - fn support_monitor_cmd(&mut self) -> Option> { - Some(self) - } - - fn support_extended_mode( - &mut self, - ) -> Option> { - Some(self) - } -} - -impl target::ext::extended_mode::ExtendedMode for XousTarget { - fn attach(&mut self, new_pid: gdbstub::common::Pid) -> TargetResult<(), Self> { - if let Some(previous_pid) = self.pid.take() { - crate::services::SystemServices::with_mut(|system_services| { - system_services - .resume_process_from_debug(previous_pid) - .unwrap() - }); - } - - // Disallow debugging the kernel. Sad times. - if new_pid.get() == 1 { - println!("Kernel cannot debug itself"); - self.pid = None; - return Ok(()); - } - - self.pid = new_pid.try_into().map(|v| Some(v)).unwrap_or(None); - if let Some(pid) = self.pid { - crate::services::SystemServices::with_mut(|system_services| { - system_services - .pause_process_for_debug(pid) - .map_err(|e| { - println!("PID {} not found", new_pid); - e - }) - .and_then(|v| { - println!("Now debugging PID {}", new_pid); - Ok(v) - }) - .ok(); - }); - } else { - println!("Invalid PID specified"); - } - Ok(()) - } - - fn kill(&mut self, pid: Option) -> TargetResult { - println!("GDB sent a kill request for pid {:?}", pid); - Ok(ShouldTerminate::No) - } - - fn restart(&mut self) -> Result<(), Self::Error> { - println!("GDB sent a restart request"); - Ok(()) - } - - fn query_if_attached( - &mut self, - _pid: gdbstub::common::Pid, - ) -> TargetResult { - println!("Querying if attached"); - Ok(AttachKind::Attach) - } - - fn run( - &mut self, - _filename: Option<&[u8]>, - _args: target::ext::extended_mode::Args<'_, '_>, - ) -> TargetResult { - println!("Trying to run command (?!)"); - Err(TargetError::NonFatal) - } -} - -impl MultiThreadBase for XousTarget { - fn read_registers( - &mut self, - regs: &mut gdbstub_arch::riscv::reg::RiscvCoreRegs, - tid: Tid, - ) -> TargetResult<(), Self> { - let Some(pid) = self.pid else { - for entry in regs.x.iter_mut() { - *entry = 0; - } - return Ok(()); - }; - - crate::services::SystemServices::with(|system_services| { - let current_pid = system_services.current_pid(); - // Actiavte the debugging process and iterate through it, - // noting down each active thread. - let debugging_pid = pid; - system_services - .get_process(debugging_pid) - .unwrap() - .activate() - .unwrap(); - let process = crate::arch::process::Process::current(); - let thread = process.thread(tid.get()); - regs.x[0] = 0; - for (dbg_reg, thr_reg) in regs.x[1..].iter_mut().zip(thread.registers.iter()) { - *dbg_reg = (*thr_reg) as u32; - } - regs.pc = (thread.sepc) as u32; - - // Restore the previous PID - system_services - .get_process(current_pid) - .unwrap() - .activate() - .unwrap(); - }); - Ok(()) - } - - fn write_registers( - &mut self, - regs: &gdbstub_arch::riscv::reg::RiscvCoreRegs, - tid: Tid, - ) -> TargetResult<(), Self> { - let Some(pid) = self.pid else { - return Ok(()) - }; - - crate::services::SystemServices::with(|system_services| { - let current_pid = system_services.current_pid(); - - // Actiavte the debugging process and iterate through it, - // noting down each active thread. - let debugging_pid = pid; - system_services - .get_process(debugging_pid) - .unwrap() - .activate() - .unwrap(); - let mut process = crate::arch::process::Process::current(); - let thread = process.thread_mut(tid.get()); - for (thr_reg, dbg_reg) in thread.registers.iter_mut().zip(regs.x[1..].iter()) { - *thr_reg = (*dbg_reg) as usize; - } - thread.sepc = (regs.pc) as usize; - - // Restore the previous PID - system_services - .get_process(current_pid) - .unwrap() - .activate() - .unwrap(); - }); - Ok(()) - } - - fn read_addrs( - &mut self, - start_addr: u32, - data: &mut [u8], - _tid: Tid, // same address space for each core - ) -> TargetResult<(), Self> { - let mut current_addr = start_addr; - let Some(pid) = self.pid else { - for entry in data.iter_mut() { *entry = 0 }; - return Ok(()); - }; - - crate::services::SystemServices::with(|system_services| { - let current_pid = system_services.current_pid(); - - // Actiavte the debugging process and iterate through it, - // noting down each active thread. - let debugging_pid = pid; - system_services - .get_process(debugging_pid) - .unwrap() - .activate() - .unwrap(); - data.iter_mut().for_each(|b| { - *b = crate::arch::mem::peek_memory(current_addr as *mut u8).unwrap_or(0xff); - current_addr += 1; - }); - - // Restore the previous PID - system_services - .get_process(current_pid) - .unwrap() - .activate() - .unwrap(); - }); - Ok(()) - } - - fn write_addrs( - &mut self, - start_addr: u32, - data: &[u8], - _tid: Tid, // same address space for each core - ) -> TargetResult<(), Self> { - let mut current_addr = start_addr; - let Some(pid) = self.pid else { - return Ok(()); - }; - crate::services::SystemServices::with(|system_services| { - let current_pid = system_services.current_pid(); - - // Actiavte the debugging process and iterate through it, - // noting down each active thread. - let debugging_pid = pid; - system_services - .get_process(debugging_pid) - .unwrap() - .activate() - .unwrap(); - data.iter().for_each(|b| { - if let Err(_e) = crate::arch::mem::poke_memory(current_addr as *mut u8, *b) { - panic!("couldn't poke memory: {:?}", _e); - // gprintln!("Error writing to {:08x}: {:?}", current_addr, e); - } - current_addr += 1; - }); - - // Restore the previous PID - system_services - .get_process(current_pid) - .unwrap() - .activate() - .unwrap(); - }); - Ok(()) - } - - fn list_active_threads( - &mut self, - register_thread: &mut dyn FnMut(Tid), - ) -> Result<(), Self::Error> { - let Some(pid) = self.pid else { - // Register a fake thread - register_thread(Tid::new(1).unwrap()); - return Ok(()); - }; - crate::services::SystemServices::with(|system_services| { - let current_pid = system_services.current_pid(); - - let debugging_pid = pid; - - // Actiavte the debugging process and iterate through it, - // noting down each active thread. - system_services - .get_process(debugging_pid) - .unwrap() - .activate() - .unwrap(); - crate::arch::process::Process::current().for_each_thread_mut(|tid, _thr| { - register_thread(Tid::new(tid).unwrap()); - }); - - // Restore the previous PID - system_services - .get_process(current_pid) - .unwrap() - .activate() - .unwrap(); - }); - Ok(()) - } - - fn support_single_register_access(&mut self) -> Option> { - Some(self) - } - - fn support_resume( - &mut self, - ) -> Option> { - Some(self) - } -} - -impl SingleRegisterAccess for XousTarget { - fn read_register( - &mut self, - tid: Tid, - reg_id: RiscvRegId, - buf: &mut [u8], - ) -> TargetResult { - // For the case of no PID, fake a value - let Some(pid) = self.pid else { - buf.copy_from_slice(&0u32.to_le_bytes()); - return Ok(buf.len()); - }; - - let reg_id = match reg_id { - RiscvRegId::Gpr(0) => { - buf.copy_from_slice(&0u32.to_le_bytes()); - return Ok(buf.len()); - } - RiscvRegId::Gpr(x) => x as usize - 1, - RiscvRegId::Pc => 32, - _ => { - return Err(TargetError::Fatal("register out of range")); - } - }; - - crate::services::SystemServices::with(|system_services| { - let current_pid = system_services.current_pid(); - // Actiavte the debugging process and iterate through it, - // noting down each active thread. - let debugging_pid = pid; - system_services - .get_process(debugging_pid) - .unwrap() - .activate() - .unwrap(); - let process = crate::arch::process::Process::current(); - let thread = process.thread(tid.get()); - let reg = if reg_id == 32 { - &thread.sepc - } else { - match thread.registers.get(reg_id) { - Some(val) => val, - None => return Err(TargetError::Fatal("register out of range")), - } - }; - - buf.copy_from_slice(®.to_le_bytes()); - - // Restore the previous PID - system_services - .get_process(current_pid) - .unwrap() - .activate() - .unwrap(); - Ok(buf.len()) - }) - } - - fn write_register( - &mut self, - tid: Tid, - reg_id: RiscvRegId, - val: &[u8], - ) -> TargetResult<(), Self> { - let Some(pid) = self.pid else { - return Ok(()) - }; - - let w = u32::from_le_bytes( - val.try_into() - .map_err(|_| TargetError::Fatal("invalid data"))?, - ); - - let reg_id = match reg_id { - RiscvRegId::Gpr(0) => { - return Ok(()); - } - RiscvRegId::Gpr(x) => x as usize - 1, - RiscvRegId::Pc => 32, - _ => { - return Err(TargetError::Fatal("register out of range")); - } - }; - - crate::services::SystemServices::with(|system_services| { - let current_pid = system_services.current_pid(); - - // Actiavte the debugging process and iterate through it, - // noting down each active thread. - let debugging_pid = pid; - system_services - .get_process(debugging_pid) - .unwrap() - .activate() - .unwrap(); - let mut process = crate::arch::process::Process::current(); - let thread = process.thread_mut(tid.get()); - let reg = if reg_id == 32 { - &mut thread.sepc - } else { - match thread.registers.get_mut(reg_id) { - Some(val) => val, - None => return Err(TargetError::Fatal("register out of range")), - } - }; - *reg = w as usize; - - // Restore the previous PID - system_services - .get_process(current_pid) - .unwrap() - .activate() - .unwrap(); - Ok(()) - }) - } -} - -impl MultiThreadResume for XousTarget { - fn resume(&mut self) -> Result<(), Self::Error> { - // println!("Resuming process {:?}", self.pid); - // unsafe { HALTED = false }; - // match default_resume_action { - // ResumeAction::Step | ResumeAction::StepWithSignal(_) => { - // return Err("single-stepping not supported") - // } - // _ => (), - // } - - if let Some(pid) = self.pid { - crate::services::SystemServices::with_mut(|system_services| { - system_services.resume_process_from_debug(pid).unwrap() - }); - } - Ok(()) - } - - fn clear_resume_actions(&mut self) -> Result<(), Self::Error> { - // println!("Clearing resume actions"); - Ok(()) - } - - fn set_resume_action_continue( - &mut self, - tid: Tid, - signal: Option, - ) -> Result<(), Self::Error> { - println!( - "Setting resume action continue on process {:?} thread {:?} with signal: {:?}", - self.pid, tid, signal - ); - // match action { - // ResumeAction::Step | ResumeAction::StepWithSignal(_) => { - // Err("single-stepping resume action not supported") - // } - // ResumeAction::Continue | ResumeAction::ContinueWithSignal(_) => Ok(()), - // } - Ok(()) - } -} - -impl target::ext::breakpoints::Breakpoints for XousTarget { - // fn support_sw_breakpoint( - // &mut self, - // ) -> Option> { - // Some(self) - // } -} - -// impl target::ext::breakpoints::SwBreakpoint for XousTarget { -// fn add_sw_breakpoint(&mut self, _addr: u32, _kind: usize) -> TargetResult { -// println!( -// "GDB asked us to add a software breakpoint at {:08x} of kind {:?}", -// _addr, _kind -// ); -// Ok(true) -// } - -// fn remove_sw_breakpoint(&mut self, _addr: u32, _kind: usize) -> TargetResult { -// println!( -// "GDB asked us to remove a software breakpoint at {:08x} of kind {:?}", -// _addr, _kind -// ); -// Ok(true) -// } -// } - -impl MonitorCmd for XousTarget { - fn handle_monitor_cmd( - &mut self, - cmd: &[u8], - mut out: target::ext::monitor_cmd::ConsoleOutput<'_>, - ) -> Result<(), Self::Error> { - let Ok(cmd) = core::str::from_utf8(cmd) else { - gdbstub::outputln!(out, "command must be valid UTF-8"); - return Ok(()); - }; - - if cmd.starts_with("pr") { - if let Some(pid_str) = cmd.split_ascii_whitespace().nth(1) { - // Parse the new PID. If it isn't a valid string, then this will be None - let new_pid = - xous_kernel::PID::new(u8::from_str_radix(pid_str, 10).unwrap_or_default()); - if let Some(previous_pid) = self.pid { - crate::services::SystemServices::with_mut(|system_services| { - system_services - .resume_process_from_debug(previous_pid) - .unwrap() - }); - } - // Disallow debugging the kernel. Sad times. - if new_pid.map(|v| v.get() == 1).unwrap_or(false) { - gdbstub::outputln!(out, "Kernel cannot debug itself"); - self.pid = None; - return Ok(()); - } - - self.pid = new_pid; - if let Some(new_pid) = self.pid { - gdbstub::outputln!(out, "Now debugging PID {}", new_pid); - crate::services::SystemServices::with_mut(|system_services| { - system_services.pause_process_for_debug(new_pid).unwrap() - }); - } else { - gdbstub::outputln!(out, "No process is selected for debugging"); - } - return Ok(()); - } - gdbstub::outputln!(out, "Available processes:"); - - crate::services::SystemServices::with(|system_services| { - for process in &system_services.processes { - if !process.free() { - gdbstub::outputln!( - out, - " {:2} {} {}", - process.pid, - if self.pid.map(|p| p == process.pid).unwrap_or(false) { - '*' - } else { - ' ' - }, - system_services.process_name(process.pid).unwrap_or("") - ); - } - } - }); - } else if cmd.starts_with("h") { - gdbstub::outputln!(out, "Here is a list of help commands:"); - gdbstub::outputln!(out, " process Print a list of processes"); - gdbstub::outputln!(out, " process [n] Switch to debugging process [n]"); - } else { - gdbstub::outputln!(out, "command not found -- try 'mon help'"); - } - Ok(()) - } -} - fn state_can_accept_characters<'a, T: Target + ProcessPid, C: Connection>( machine: &GdbStubStateMachine<'a, T, C>, ) -> bool { diff --git a/kernel/src/debug/gdb/breakpoints.rs b/kernel/src/debug/gdb/breakpoints.rs new file mode 100644 index 000000000..cd8c60e40 --- /dev/null +++ b/kernel/src/debug/gdb/breakpoints.rs @@ -0,0 +1,29 @@ +use gdbstub::target::ext::breakpoints::Breakpoints; + +use super::XousTarget; + +impl Breakpoints for XousTarget { + // fn support_sw_breakpoint( + // &mut self, + // ) -> Option> { + // Some(self) + // } +} + +// impl target::ext::breakpoints::SwBreakpoint for XousTarget { +// fn add_sw_breakpoint(&mut self, _addr: u32, _kind: usize) -> TargetResult { +// println!( +// "GDB asked us to add a software breakpoint at {:08x} of kind {:?}", +// _addr, _kind +// ); +// Ok(true) +// } + +// fn remove_sw_breakpoint(&mut self, _addr: u32, _kind: usize) -> TargetResult { +// println!( +// "GDB asked us to remove a software breakpoint at {:08x} of kind {:?}", +// _addr, _kind +// ); +// Ok(true) +// } +// } diff --git a/kernel/src/debug/gdb/extended_mode.rs b/kernel/src/debug/gdb/extended_mode.rs new file mode 100644 index 000000000..f1cd57aa1 --- /dev/null +++ b/kernel/src/debug/gdb/extended_mode.rs @@ -0,0 +1,72 @@ +use gdbstub::target; +use gdbstub::target::ext::extended_mode::{AttachKind, ShouldTerminate}; +use gdbstub::target::{TargetError, TargetResult}; + +use super::XousTarget; +use core::convert::TryInto; + +impl target::ext::extended_mode::ExtendedMode for XousTarget { + fn attach(&mut self, new_pid: gdbstub::common::Pid) -> TargetResult<(), Self> { + if let Some(previous_pid) = self.pid.take() { + crate::services::SystemServices::with_mut(|system_services| { + system_services + .resume_process_from_debug(previous_pid) + .unwrap() + }); + } + + // Disallow debugging the kernel. Sad times. + if new_pid.get() == 1 { + println!("Kernel cannot debug itself"); + self.pid = None; + return Ok(()); + } + + self.pid = new_pid.try_into().map(|v| Some(v)).unwrap_or(None); + if let Some(pid) = self.pid { + crate::services::SystemServices::with_mut(|system_services| { + system_services + .pause_process_for_debug(pid) + .map_err(|e| { + println!("PID {} not found", new_pid); + e + }) + .and_then(|v| { + println!("Now debugging PID {}", new_pid); + Ok(v) + }) + .ok(); + }); + } else { + println!("Invalid PID specified"); + } + Ok(()) + } + + fn kill(&mut self, pid: Option) -> TargetResult { + println!("GDB sent a kill request for pid {:?}", pid); + Ok(ShouldTerminate::No) + } + + fn restart(&mut self) -> Result<(), Self::Error> { + println!("GDB sent a restart request"); + Ok(()) + } + + fn query_if_attached( + &mut self, + _pid: gdbstub::common::Pid, + ) -> TargetResult { + println!("Querying if attached"); + Ok(AttachKind::Attach) + } + + fn run( + &mut self, + _filename: Option<&[u8]>, + _args: target::ext::extended_mode::Args<'_, '_>, + ) -> TargetResult { + println!("Trying to run command (?!)"); + Err(TargetError::NonFatal) + } +} diff --git a/kernel/src/debug/gdb/monitor.rs b/kernel/src/debug/gdb/monitor.rs new file mode 100644 index 000000000..068922c55 --- /dev/null +++ b/kernel/src/debug/gdb/monitor.rs @@ -0,0 +1,75 @@ +use gdbstub::target; +use gdbstub::target::ext::monitor_cmd::MonitorCmd; + +use super::XousTarget; + +impl MonitorCmd for XousTarget { + fn handle_monitor_cmd( + &mut self, + cmd: &[u8], + mut out: target::ext::monitor_cmd::ConsoleOutput<'_>, + ) -> Result<(), Self::Error> { + let Ok(cmd) = core::str::from_utf8(cmd) else { + gdbstub::outputln!(out, "command must be valid UTF-8"); + return Ok(()); + }; + + if cmd.starts_with("pr") { + if let Some(pid_str) = cmd.split_ascii_whitespace().nth(1) { + // Parse the new PID. If it isn't a valid string, then this will be None + let new_pid = + xous_kernel::PID::new(u8::from_str_radix(pid_str, 10).unwrap_or_default()); + if let Some(previous_pid) = self.pid { + crate::services::SystemServices::with_mut(|system_services| { + system_services + .resume_process_from_debug(previous_pid) + .unwrap() + }); + } + // Disallow debugging the kernel. Sad times. + if new_pid.map(|v| v.get() == 1).unwrap_or(false) { + gdbstub::outputln!(out, "Kernel cannot debug itself"); + self.pid = None; + return Ok(()); + } + + self.pid = new_pid; + if let Some(new_pid) = self.pid { + gdbstub::outputln!(out, "Now debugging PID {}", new_pid); + crate::services::SystemServices::with_mut(|system_services| { + system_services.pause_process_for_debug(new_pid).unwrap() + }); + } else { + gdbstub::outputln!(out, "No process is selected for debugging"); + } + return Ok(()); + } + gdbstub::outputln!(out, "Available processes:"); + + crate::services::SystemServices::with(|system_services| { + for process in &system_services.processes { + if !process.free() { + gdbstub::outputln!( + out, + " {:2} {} {}", + process.pid, + if self.pid.map(|p| p == process.pid).unwrap_or(false) { + '*' + } else { + ' ' + }, + system_services.process_name(process.pid).unwrap_or("") + ); + } + } + }); + } else if cmd.starts_with("h") { + gdbstub::outputln!(out, "Here is a list of help commands:"); + gdbstub::outputln!(out, " process Print a list of processes"); + gdbstub::outputln!(out, " process [n] Switch to debugging process [n]"); + } else { + gdbstub::outputln!(out, "command not found -- try 'mon help'"); + } + Ok(()) + } +} diff --git a/kernel/src/debug/gdb/multi_thread_base.rs b/kernel/src/debug/gdb/multi_thread_base.rs new file mode 100644 index 000000000..50828a116 --- /dev/null +++ b/kernel/src/debug/gdb/multi_thread_base.rs @@ -0,0 +1,208 @@ +use gdbstub::common::Tid; +use gdbstub::target; +use gdbstub::target::ext::base::multithread::MultiThreadBase; +use gdbstub::target::ext::base::single_register_access::SingleRegisterAccessOps; +use gdbstub::target::TargetResult; + +use super::XousTarget; + +impl MultiThreadBase for XousTarget { + fn read_registers( + &mut self, + regs: &mut gdbstub_arch::riscv::reg::RiscvCoreRegs, + tid: Tid, + ) -> TargetResult<(), Self> { + let Some(pid) = self.pid else { + for entry in regs.x.iter_mut() { + *entry = 0; + } + return Ok(()); + }; + + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + // Actiavte the debugging process and iterate through it, + // noting down each active thread. + let debugging_pid = pid; + system_services + .get_process(debugging_pid) + .unwrap() + .activate() + .unwrap(); + let process = crate::arch::process::Process::current(); + let thread = process.thread(tid.get()); + regs.x[0] = 0; + for (dbg_reg, thr_reg) in regs.x[1..].iter_mut().zip(thread.registers.iter()) { + *dbg_reg = (*thr_reg) as u32; + } + regs.pc = (thread.sepc) as u32; + + // Restore the previous PID + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + }); + Ok(()) + } + + fn write_registers( + &mut self, + regs: &gdbstub_arch::riscv::reg::RiscvCoreRegs, + tid: Tid, + ) -> TargetResult<(), Self> { + let Some(pid) = self.pid else { + return Ok(()) + }; + + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + + // Actiavte the debugging process and iterate through it, + // noting down each active thread. + let debugging_pid = pid; + system_services + .get_process(debugging_pid) + .unwrap() + .activate() + .unwrap(); + let mut process = crate::arch::process::Process::current(); + let thread = process.thread_mut(tid.get()); + for (thr_reg, dbg_reg) in thread.registers.iter_mut().zip(regs.x[1..].iter()) { + *thr_reg = (*dbg_reg) as usize; + } + thread.sepc = (regs.pc) as usize; + + // Restore the previous PID + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + }); + Ok(()) + } + + fn read_addrs( + &mut self, + start_addr: u32, + data: &mut [u8], + _tid: Tid, // same address space for each core + ) -> TargetResult<(), Self> { + let mut current_addr = start_addr; + let Some(pid) = self.pid else { + for entry in data.iter_mut() { *entry = 0 }; + return Ok(()); + }; + + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + + // Actiavte the debugging process and iterate through it, + // noting down each active thread. + let debugging_pid = pid; + system_services + .get_process(debugging_pid) + .unwrap() + .activate() + .unwrap(); + data.iter_mut().for_each(|b| { + *b = crate::arch::mem::peek_memory(current_addr as *mut u8).unwrap_or(0xff); + current_addr += 1; + }); + + // Restore the previous PID + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + }); + Ok(()) + } + + fn write_addrs( + &mut self, + start_addr: u32, + data: &[u8], + _tid: Tid, // same address space for each core + ) -> TargetResult<(), Self> { + let mut current_addr = start_addr; + let Some(pid) = self.pid else { + return Ok(()); + }; + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + + // Actiavte the debugging process and iterate through it, + // noting down each active thread. + let debugging_pid = pid; + system_services + .get_process(debugging_pid) + .unwrap() + .activate() + .unwrap(); + data.iter().for_each(|b| { + if let Err(_e) = crate::arch::mem::poke_memory(current_addr as *mut u8, *b) { + panic!("couldn't poke memory: {:?}", _e); + // gprintln!("Error writing to {:08x}: {:?}", current_addr, e); + } + current_addr += 1; + }); + + // Restore the previous PID + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + }); + Ok(()) + } + + fn list_active_threads( + &mut self, + register_thread: &mut dyn FnMut(Tid), + ) -> Result<(), Self::Error> { + let Some(pid) = self.pid else { + // Register a fake thread + register_thread(Tid::new(1).unwrap()); + return Ok(()); + }; + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + + let debugging_pid = pid; + + // Actiavte the debugging process and iterate through it, + // noting down each active thread. + system_services + .get_process(debugging_pid) + .unwrap() + .activate() + .unwrap(); + crate::arch::process::Process::current().for_each_thread_mut(|tid, _thr| { + register_thread(Tid::new(tid).unwrap()); + }); + + // Restore the previous PID + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + }); + Ok(()) + } + + fn support_single_register_access(&mut self) -> Option> { + Some(self) + } + + fn support_resume( + &mut self, + ) -> Option> { + Some(self) + } +} diff --git a/kernel/src/debug/gdb/multi_thread_resume.rs b/kernel/src/debug/gdb/multi_thread_resume.rs new file mode 100644 index 000000000..37a14f939 --- /dev/null +++ b/kernel/src/debug/gdb/multi_thread_resume.rs @@ -0,0 +1,47 @@ +use gdbstub::common::{Signal, Tid}; +use gdbstub::target::ext::base::multithread::MultiThreadResume; + +use super::XousTarget; + +impl MultiThreadResume for XousTarget { + fn resume(&mut self) -> Result<(), Self::Error> { + // println!("Resuming process {:?}", self.pid); + // unsafe { HALTED = false }; + // match default_resume_action { + // ResumeAction::Step | ResumeAction::StepWithSignal(_) => { + // return Err("single-stepping not supported") + // } + // _ => (), + // } + + if let Some(pid) = self.pid { + crate::services::SystemServices::with_mut(|system_services| { + system_services.resume_process_from_debug(pid).unwrap() + }); + } + Ok(()) + } + + fn clear_resume_actions(&mut self) -> Result<(), Self::Error> { + // println!("Clearing resume actions"); + Ok(()) + } + + fn set_resume_action_continue( + &mut self, + tid: Tid, + signal: Option, + ) -> Result<(), Self::Error> { + println!( + "Setting resume action continue on process {:?} thread {:?} with signal: {:?}", + self.pid, tid, signal + ); + // match action { + // ResumeAction::Step | ResumeAction::StepWithSignal(_) => { + // Err("single-stepping resume action not supported") + // } + // ResumeAction::Continue | ResumeAction::ContinueWithSignal(_) => Ok(()), + // } + Ok(()) + } +} diff --git a/kernel/src/debug/gdb/riscv.rs b/kernel/src/debug/gdb/riscv.rs new file mode 100644 index 000000000..e69de29bb diff --git a/kernel/src/debug/gdb/single_register_access.rs b/kernel/src/debug/gdb/single_register_access.rs new file mode 100644 index 000000000..9b60bc802 --- /dev/null +++ b/kernel/src/debug/gdb/single_register_access.rs @@ -0,0 +1,125 @@ +use gdbstub::common::Tid; +use gdbstub::target::ext::base::single_register_access::SingleRegisterAccess; +use gdbstub::target::{TargetError, TargetResult}; +use gdbstub_arch::riscv::reg::id::RiscvRegId; + +use super::XousTarget; +use core::convert::TryInto; + +impl SingleRegisterAccess for XousTarget { + fn read_register( + &mut self, + tid: Tid, + reg_id: RiscvRegId, + buf: &mut [u8], + ) -> TargetResult { + // For the case of no PID, fake a value + let Some(pid) = self.pid else { + buf.copy_from_slice(&0u32.to_le_bytes()); + return Ok(buf.len()); + }; + + let reg_id = match reg_id { + RiscvRegId::Gpr(0) => { + buf.copy_from_slice(&0u32.to_le_bytes()); + return Ok(buf.len()); + } + RiscvRegId::Gpr(x) => x as usize - 1, + RiscvRegId::Pc => 32, + _ => { + return Err(TargetError::Fatal("register out of range")); + } + }; + + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + // Actiavte the debugging process and iterate through it, + // noting down each active thread. + let debugging_pid = pid; + system_services + .get_process(debugging_pid) + .unwrap() + .activate() + .unwrap(); + let process = crate::arch::process::Process::current(); + let thread = process.thread(tid.get()); + let reg = if reg_id == 32 { + &thread.sepc + } else { + match thread.registers.get(reg_id) { + Some(val) => val, + None => return Err(TargetError::Fatal("register out of range")), + } + }; + + buf.copy_from_slice(®.to_le_bytes()); + + // Restore the previous PID + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + Ok(buf.len()) + }) + } + + fn write_register( + &mut self, + tid: Tid, + reg_id: RiscvRegId, + val: &[u8], + ) -> TargetResult<(), Self> { + let Some(pid) = self.pid else { + return Ok(()) + }; + + let w = u32::from_le_bytes( + val.try_into() + .map_err(|_| TargetError::Fatal("invalid data"))?, + ); + + let reg_id = match reg_id { + RiscvRegId::Gpr(0) => { + return Ok(()); + } + RiscvRegId::Gpr(x) => x as usize - 1, + RiscvRegId::Pc => 32, + _ => { + return Err(TargetError::Fatal("register out of range")); + } + }; + + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + + // Actiavte the debugging process and iterate through it, + // noting down each active thread. + let debugging_pid = pid; + system_services + .get_process(debugging_pid) + .unwrap() + .activate() + .unwrap(); + let mut process = crate::arch::process::Process::current(); + let thread = process.thread_mut(tid.get()); + let reg = if reg_id == 32 { + &mut thread.sepc + } else { + match thread.registers.get_mut(reg_id) { + Some(val) => val, + None => return Err(TargetError::Fatal("register out of range")), + } + }; + *reg = w as usize; + + // Restore the previous PID + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + Ok(()) + }) + } +} diff --git a/kernel/src/debug/gdb/target.rs b/kernel/src/debug/gdb/target.rs new file mode 100644 index 000000000..b40232b9b --- /dev/null +++ b/kernel/src/debug/gdb/target.rs @@ -0,0 +1,34 @@ +use gdbstub::target::ext::base::BaseOps; +use gdbstub::target::ext::breakpoints::BreakpointsOps; +use gdbstub::target::ext::extended_mode::ExtendedModeOps; +use gdbstub::target::ext::monitor_cmd::MonitorCmdOps; +use gdbstub::target::Target; + +use super::XousTarget; + +impl Target for XousTarget { + type Arch = gdbstub_arch::riscv::Riscv32; + type Error = &'static str; + + fn base_ops(&mut self) -> BaseOps { + BaseOps::MultiThread(self) + } + + fn support_breakpoints(&mut self) -> Option> { + Some(self) + } + + /// Opt in to having GDB handle breakpoints for us. This allows for an unlimited number + /// of breakpoints without having us keep track of the breakpoints ourselves. + fn guard_rail_implicit_sw_breakpoints(&self) -> bool { + true + } + + fn support_monitor_cmd(&mut self) -> Option> { + Some(self) + } + + fn support_extended_mode(&mut self) -> Option> { + Some(self) + } +}