From 13029a76a238c915f0afe204e1904cc8e5b2bf17 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 6 Apr 2023 10:45:42 +0800 Subject: [PATCH] kernel: initial gdb-stub reimplementation Add an initial reimplementation of the gdb-stub using the gdbstub backing crate. This supports process enumeration and basic thread investigation. Processes will pause when the debugger is inspecting them. Memory and registers can be investigated. Threads can be listed and selected. It does not yet support breakpoints. Signed-off-by: Sean Cross --- kernel/Cargo.toml | 4 +- kernel/src/debug/gdb.rs | 678 +++++++++++++++++++++++ kernel/src/debug/mod.rs | 3 + kernel/src/platform/precursor/gdbuart.rs | 130 +++++ kernel/src/platform/precursor/mod.rs | 6 + kernel/src/services.rs | 100 +++- 6 files changed, 904 insertions(+), 17 deletions(-) create mode 100644 kernel/src/debug/gdb.rs create mode 100644 kernel/src/platform/precursor/gdbuart.rs diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 171d73140..b8d470450 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -24,6 +24,8 @@ xous-kernel = { package = "xous", version = "0.9.37", features = [ [target.'cfg(target_arch = "riscv32")'.dependencies] riscv = { version = "0.5.6", package = "xous-riscv" } # source is in "../imports/riscv-0.5.6" +gdbstub = { version = "0.6.4", optional = true, default-features = false } +gdbstub_arch = { version = "0.2.4", optional = true, default-features = false } [target.'cfg(target_arch = "arm")'.dependencies] armv7 = { git = "https://github.com/Foundation-Devices/armv7.git", branch = "update", features = ["critical-section"] } @@ -40,7 +42,7 @@ hosted = ["utralib/hosted"] renode = ["utralib/renode"] debug-print = [] -gdb-stub = [] +gdb-stub = ["gdbstub", "gdbstub_arch"] print-panics = [] report-memory = ["stats_alloc"] wrap-print = [] diff --git a/kernel/src/debug/gdb.rs b/kernel/src/debug/gdb.rs new file mode 100644 index 000000000..c05177acd --- /dev/null +++ b/kernel/src/debug/gdb.rs @@ -0,0 +1,678 @@ +use gdbstub::common::{Signal, Tid}; +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::monitor_cmd::MonitorCmd; +use gdbstub::target::TargetError; +use gdbstub::target::{Target, TargetResult}; +use gdbstub_arch::riscv::reg::id::RiscvRegId; + +use crate::io::SerialRead; +use crate::platform::precursor::gdbuart::GdbUart; + +use core::convert::TryInto; + +pub struct XousTarget { + pid: Option, +} +pub struct XousDebugState<'a> { + pub target: XousTarget, + pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>, +} + +pub static mut GDB_STATE: Option = None; +pub static mut GDB_BUFFER: [u8; 4096] = [0u8; 4096]; + +fn receive_irq(uart: &mut GdbUart) { + while let Some(c) = uart.getc() { + advance_gdb_or_recreate(Some(c)); + } +} + +impl XousTarget { + pub fn new() -> XousTarget { + XousTarget { pid: None } + } +} + +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) + } + + fn support_monitor_cmd(&mut self) -> Option> { + Some(self) + } +} + +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 { + #[inline(always)] + fn support_sw_breakpoint( + &mut self, + ) -> Option> { + Some(self) + } +} + +impl target::ext::breakpoints::SwBreakpoint for XousTarget { + #[inline(never)] + 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) + } + + #[inline(never)] + 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 advance_gdb_or_recreate(byte: Option) { + advance_gdb_state(byte); + if unsafe { GDB_STATE.is_none() } { + println!("GDB went away -- recreating it"); + init(); + } +} + +fn advance_gdb_state(byte: Option) -> bool { + let Some(XousDebugState { + mut target, + server: gdb, + }) = (unsafe { GDB_STATE.take() }) else { + println!("No GDB!"); + return false; + }; + + let mut new_gdb = match gdb { + GdbStubStateMachine::Idle(gdb_stm_inner) => match byte { + Some(byte) => match gdb_stm_inner.incoming_data(&mut target, byte) { + Ok(gdb) => gdb, + Err(e) => { + println!("gdbstub error during idle operation: {:?}", e); + return true; + } + }, + None => { + println!("gdbstub was idle with no characters?!"); + GdbStubStateMachine::Idle(gdb_stm_inner) + } + }, + + GdbStubStateMachine::Running(gdb_stm_inner) => { + // If we're here we were running but have stopped now (either + // because we hit Ctrl+c in gdb and hence got a serial interrupt + // or we hit a breakpoint). + // let conn = gdb_stm_inner.borrow_conn(); + // conn.disable_irq(); + // let data_to_read = conn.peek().unwrap().is_some(); + // let mut stop_reason = target.determine_stop_reason(reason); + + if let Some(byte) = byte { + match gdb_stm_inner.incoming_data(&mut target, byte) { + Ok(pumped_stm) => { + if let GdbStubStateMachine::CtrlCInterrupt(_) = pumped_stm { + println!( + "Looks like we maybe just transitioned from running to ctrl-c?" + ); + } else if let GdbStubStateMachine::Idle(_) = pumped_stm { + println!("Looks like we maybe just transitioned from running to idle?"); + } + pumped_stm + } + Err(GdbStubError::TargetError(e)) => { + println!("Target raised a fatal error: {:?}", e); + return false; + } + Err(e) => { + println!("gdbstub error in DeferredStopReason.pump: {:?}", e); + return false; + } + } + // } else if let Some(reason) = stop_reason.take() { + // match gdb_stm_inner.report_stop(&mut target, MultiThreadStopReason::DoneStep) { + // Ok(gdb_stm_new) => gdb_stm_new, + // Err(GdbStubError::TargetError(e)) => { + // println!("Target raised a fatal error {:?}", e); + // return false; + // } + // Err(e) => { + // println!("gdbstub internal error {:?}", e); + // return false; + // } + // } + // } else if target.resume_with.is_some() { + // // // We don't have a `stop_reason` and we don't have something + // // // to read on the line. This probably means we're done and + // // // we should run again. + // // conn.enable_irq(); + // // let r = GDB_STUB + // // .lock() + // // .replace(GdbStubStateMachine::Running(gdb_stm_inner)); + // // assert!( + // // r.is_none(), + // // "Put something in GDB_STUB which we shouldn't have..." + // // ); + // // return false; + // GdbStubStateMachine::Running(gdb_stm_inner) + } else { + panic!("Can't happen?"); + } + } + + GdbStubStateMachine::CtrlCInterrupt(_gdb_stm_inner) => { + panic!("debug server was in an unexpected state"); + } + + GdbStubStateMachine::Disconnected(_gdb_stm_inner) => { + println!("GdbStubStateMachine::Disconnected byebye"); + return false; + } + }; + + if let GdbStubStateMachine::CtrlCInterrupt(gdb_stm_inner) = new_gdb { + println!("Just transitioned into CtrlCInterrupt"); + match gdb_stm_inner.interrupt_handled(&mut target, Some(MultiThreadStopReason::DoneStep)) { + Ok(gdb) => new_gdb = gdb, + Err(e) => { + println!("gdbstub error during ctrl-c interrupt{:?}", e); + return false; + } + } + + if let Some(pid) = target.pid { + println!("Starting debug on process {:?}", pid); + crate::services::SystemServices::with_mut(|system_services| { + system_services.pause_process_for_debug(pid).unwrap() + }); + } else { + println!("No process specified! Not debugging"); + } + } + + unsafe { + GDB_STATE = Some(XousDebugState { + target, + server: new_gdb, + }) + }; + true +} + +pub fn init() { + let uart = GdbUart::new(receive_irq).unwrap(); + let mut target = XousTarget::new(); + + match GdbStubBuilder::new(uart) + .with_packet_buffer(unsafe { &mut GDB_BUFFER }) + .build() + { + Ok(gdb) => match gdb.run_state_machine(&mut target) { + Ok(state) => unsafe { + GDB_STATE = Some(XousDebugState { + target: target, + server: state, + }); + HALTED = true; + }, + Err(e) => println!("Unable to start GDB state machine: {}", e), + }, + Err(e) => println!("Unable to start GDB server: {}", e), + } +} + +static mut HALTED: bool = false; diff --git a/kernel/src/debug/mod.rs b/kernel/src/debug/mod.rs index 04452ee3e..e7216bbec 100644 --- a/kernel/src/debug/mod.rs +++ b/kernel/src/debug/mod.rs @@ -5,3 +5,6 @@ mod macros; #[cfg(baremetal)] pub mod shell; + +#[cfg(all(baremetal, feature = "gdb-stub"))] +pub mod gdb; diff --git a/kernel/src/platform/precursor/gdbuart.rs b/kernel/src/platform/precursor/gdbuart.rs new file mode 100644 index 000000000..ed7ced7cf --- /dev/null +++ b/kernel/src/platform/precursor/gdbuart.rs @@ -0,0 +1,130 @@ +// SPDX-FileCopyrightText: 2020 Sean Cross +// SPDX-FileCopyrightText: 2022 Foundation Devices, Inc. +// SPDX-License-Identifier: Apache-2.0 + +use crate::{ + io::{SerialRead, SerialWrite}, + mem::MemoryManager, + PID, +}; +use core::sync::atomic::{AtomicUsize, Ordering}; +use utralib::generated::*; +use xous_kernel::{MemoryFlags, MemoryType}; + +static UART_USAGE_COUNT: AtomicUsize = AtomicUsize::new(0); + +/// UART virtual address. +/// +/// See https://github.com/betrusted-io/xous-core/blob/master/docs/memory.md +pub const APP_UART_ADDR: usize = 0xffcc_0000; + +/// UART peripheral driver. +pub struct GdbUart { + uart_csr: CSR, + callback: fn(&mut Self), +} + +impl GdbUart { + pub fn new(callback: fn(&mut Self)) -> Option { + if UART_USAGE_COUNT + .compare_exchange(0, 1, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { + return None; + } + + // Map the UART peripheral. + MemoryManager::with_mut(|memory_manager| { + memory_manager + .map_range( + utra::app_uart::HW_APP_UART_BASE as *mut u8, + (APP_UART_ADDR & !4095) as *mut u8, + 4096, + PID::new(1).unwrap(), + MemoryFlags::R | MemoryFlags::W, + MemoryType::Default, + ) + .expect("unable to map serial port") + }); + let mut gdb_uart = GdbUart { + uart_csr: CSR::new(APP_UART_ADDR as *mut u32), + callback, + }; + + xous_kernel::claim_interrupt( + utra::app_uart::APP_UART_IRQ, + GdbUart::irq, + (&mut gdb_uart as *mut GdbUart) as *mut usize, + ) + .expect("Couldn't claim debug interrupt"); + + Some(gdb_uart) + } + + pub fn enable(&mut self) { + self.uart_csr.rmwf(utra::app_uart::EV_ENABLE_RX, 1); + } + + pub fn irq(_irq_number: usize, arg: *mut usize) { + let uart = unsafe { &mut *(arg as *mut GdbUart) }; + (uart.callback)(uart); + } +} + +impl Drop for GdbUart { + fn drop(&mut self) { + if UART_USAGE_COUNT.fetch_sub(1, Ordering::Relaxed) != 1 { + panic!("UART ad a usage count of more than 1"); + } + + println!("Freeing interrupt since the count has gone to zero"); + xous_kernel::rsyscall(xous_kernel::SysCall::FreeInterrupt( + utra::app_uart::APP_UART_IRQ, + )) + .unwrap(); + + MemoryManager::with_mut(|memory_manager| { + memory_manager + .unmap_page((APP_UART_ADDR & !4095) as *mut usize) + .unwrap() + }); + } +} + +impl SerialWrite for GdbUart { + fn putc(&mut self, c: u8) { + // Wait until TXFULL is `0` + while self.uart_csr.r(utra::app_uart::TXFULL) != 0 {} + self.uart_csr.wfo(utra::app_uart::RXTX_RXTX, c as u32); + } +} + +impl SerialRead for GdbUart { + fn getc(&mut self) -> Option { + // If EV_PENDING_RX is 1, return the pending character. + // Otherwise, return None. + match self.uart_csr.rf(utra::app_uart::EV_PENDING_RX) { + 0 => None, + _ => { + let ret = Some(self.uart_csr.r(utra::app_uart::RXTX) as u8); + self.uart_csr.wfo(utra::app_uart::EV_PENDING_RX, 1); + ret + } + } + } +} + +impl gdbstub::conn::Connection for GdbUart { + type Error = &'static str; + fn write(&mut self, byte: u8) -> Result<(), Self::Error> { + self.putc(byte); + Ok(()) + } + fn flush(&mut self) -> Result<(), Self::Error> { + Ok(()) + } + fn on_session_start(&mut self) -> Result<(), Self::Error> { + self.enable(); + Ok(()) + } +} diff --git a/kernel/src/platform/precursor/mod.rs b/kernel/src/platform/precursor/mod.rs index c1eac021b..6e4a2c396 100644 --- a/kernel/src/platform/precursor/mod.rs +++ b/kernel/src/platform/precursor/mod.rs @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: 2022 Foundation Devices, Inc. // SPDX-License-Identifier: Apache-2.0 +#[cfg(feature = "gdb-stub")] +pub mod gdbuart; pub mod rand; #[cfg(any(feature = "debug-print", feature = "print-panics"))] pub mod uart; @@ -8,6 +10,10 @@ pub mod uart; /// Precursor specific initialization. pub fn init() { self::rand::init(); + #[cfg(any(feature = "debug-print", feature = "print-panics"))] self::uart::init(); + + #[cfg(feature = "gdb-stub")] + crate::debug::gdb::init(); } diff --git a/kernel/src/services.rs b/kernel/src/services.rs index 5e8ace002..564b80bbc 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -86,9 +86,15 @@ pub enum ProcessState { /// The process is currently being debugged. When it is resumed, /// this will turn into `Ready(usize)` - #[allow(dead_code)] + #[cfg(feature = "gdb-stub")] Debug(usize), + /// The process is currently being debugged, but an interrupt happened + /// anyway. When the interrupt finishes, this will turn into `Debug(usize)`. + /// This generally should not happen, but is here in case NMIs are ever a thing. + #[cfg(feature = "gdb-stub")] + DebugIrq(usize), + /// This process is processing an exception. When it is resumed, it will /// turn into `Ready(usize)`. Exception(usize), @@ -107,7 +113,10 @@ impl core::fmt::Debug for ProcessState { Setup(ti) => write!(fmt, "Setup({:?})", ti), Ready(rt) => write!(fmt, "Ready({:b})", rt), Running(rt) => write!(fmt, "Running({:b})", rt), + #[cfg(feature = "gdb-stub")] Debug(rt) => write!(fmt, "Debug({:b})", rt), + #[cfg(feature = "gdb-stub")] + DebugIrq(rt) => write!(fmt, "DebugIrq({:b})", rt), Exception(rt) => write!(fmt, "Exception({:b})", rt), BlockedException(rt) => write!(fmt, "BlockedException({:b})", rt), Sleeping => write!(fmt, "Sleeping"), @@ -343,7 +352,9 @@ impl SystemServices { let init_offsets = { let mut init_count = 1; for arg in args.iter() { - if arg.name == u32::from_le_bytes(*b"IniE") || arg.name == u32::from_le_bytes(*b"IniF") { + if arg.name == u32::from_le_bytes(*b"IniE") + || arg.name == u32::from_le_bytes(*b"IniF") + { init_count += 1; } } @@ -557,6 +568,8 @@ impl SystemServices { current.state = match current.state { ProcessState::Running(0) => ProcessState::Sleeping, ProcessState::Running(x) => ProcessState::Ready(x), + #[cfg(feature = "gdb-stub")] + ProcessState::DebugIrq(x) => ProcessState::Debug(x), y => panic!("current process was {:?}, not 'Running(_)'", y), }; // log_process_update(file!(), line!(), current, old_state); @@ -568,12 +581,14 @@ impl SystemServices { // is in a very bad state. { let mut process = self.get_process_mut(pid)?; + #[cfg(feature = "gdb-stub")] let ppid = process.ppid; // Ensure the new context is available to be run let available_threads = match process.state { ProcessState::Ready(x) if x & 1 << tid != 0 => x & !(1 << tid), // If we're currently debugging the process, return to its parent. // This can happen when the process handles a debug interrupt. + #[cfg(feature = "gdb-stub")] ProcessState::Debug(_) => { crate::syscall::reset_switchto_caller(); return self.switch_to_thread(ppid, None); @@ -654,18 +669,29 @@ impl SystemServices { { let mut process = self.get_process_mut(pid)?; let available_threads = match process.state { - ProcessState::Ready(x) - | ProcessState::Running(x) - | ProcessState::Debug(x) - | ProcessState::Exception(x) => x, + ProcessState::Ready(x) | ProcessState::Running(x) | ProcessState::Exception(x) => x, + #[cfg(feature = "gdb-stub")] + ProcessState::Debug(x) | ProcessState::DebugIrq(x) => x, ProcessState::Sleeping | ProcessState::BlockedException(_) => 0, ProcessState::Free => panic!("process was not allocated"), ProcessState::Setup(_) | ProcessState::Allocated => { panic!("process hasn't been set up yet") } }; + #[cfg(feature = "gdb-stub")] + if let ProcessState::Debug(_) = process.state { + println!("Making a callback for IRQ {} to process {:?} which is currently in a debug state!", irq_no, pid); + process.state = ProcessState::DebugIrq(available_threads); + } else { + process.state = ProcessState::Running(available_threads); + } + // let old_state = process.state; - process.state = ProcessState::Running(available_threads); + #[cfg(not(feature = "gdb-stub"))] + { + process.state = ProcessState::Running(available_threads); + } + // log_process_update(file!(), line!(), process, old_state); process.previous_thread = process.current_thread; process.current_thread = arch::process::IRQ_TID; @@ -734,7 +760,12 @@ impl SystemServices { } ProcessState::Ready(x) if x & (1 << tid) == 0 => ProcessState::Ready(x | (1 << tid)), ProcessState::Sleeping => ProcessState::Ready(1 << tid), + #[cfg(feature = "gdb-stub")] ProcessState::Debug(x) if x & (1 << tid) == 0 => ProcessState::Debug(x | (1 << tid)), + #[cfg(feature = "gdb-stub")] + ProcessState::DebugIrq(x) if x & (1 << tid) == 0 => { + ProcessState::DebugIrq(x | (1 << tid)) + } ProcessState::Exception(ready_threads) | ProcessState::BlockedException(ready_threads) => { ProcessState::Exception(ready_threads) @@ -845,7 +876,10 @@ impl SystemServices { ProcessState::BlockedException(_) => { panic!("tried to switch to an exception handler that was blocked") } - ProcessState::Debug(_) => return Err(xous_kernel::Error::DebugInProgress), + #[cfg(feature = "gdb-stub")] + ProcessState::Debug(_) | ProcessState::DebugIrq(_) => { + return Err(xous_kernel::Error::DebugInProgress) + } ProcessState::Exception(x) => { process.activate()?; let mut p = ArchProcess::current(); @@ -1083,9 +1117,11 @@ impl SystemServices { ProcessState::Running(_) => { panic!("process was running even though the pid was different") } - ProcessState::Sleeping - | ProcessState::Debug(_) - | ProcessState::BlockedException(_) => { + #[cfg(feature = "gdb-stub")] + ProcessState::Debug(_) | ProcessState::DebugIrq(_) => { + return Err(xous_kernel::Error::ProcessNotFound) + } + ProcessState::Sleeping | ProcessState::BlockedException(_) => { // println!("PID {} was sleeping or being debugged", new_pid); return Err(xous_kernel::Error::ProcessNotFound); } @@ -1121,7 +1157,10 @@ impl SystemServices { ProcessState::BlockedException(_) => { panic!("process was blocked handling an exception") } - ProcessState::Debug(_) => panic!("process was being debugged"), + #[cfg(feature = "gdb-stub")] + ProcessState::Debug(_) | ProcessState::DebugIrq(_) => { + panic!("process was being debugged") + } }; // log_process_update(file!(), line!(), new, old_state); new.activate()?; @@ -2215,11 +2254,24 @@ impl SystemServices { } #[cfg(feature = "gdb-stub")] - pub fn suspend_process(&mut self, pid: PID) -> Result<(), xous_kernel::Error> { + pub fn pause_process_for_debug(&mut self, pid: PID) -> Result<(), xous_kernel::Error> { + println!("Pausing process {:?} for debug...", pid); let (process_state, parent_pid) = { let process = self.get_process_mut(pid)?; (process.state, process.ppid) }; + + // Disable all interrupts that belong to this process + crate::irq::for_each_irq(|irq_no, irq_pid, _, _| { + println!("Examining IRQ {}...", irq_no); + if pid == *irq_pid { + println!( + "Disabling IRQ {} since it's owned by process {:?}", + irq_no, pid + ); + crate::arch::irq::disable_irq(irq_no); + } + }); let new_process_state = match process_state { ProcessState::Allocated => ProcessState::Allocated, ProcessState::Free => ProcessState::Free, @@ -2229,6 +2281,7 @@ impl SystemServices { ProcessState::BlockedException(tids) => ProcessState::BlockedException(tids), ProcessState::Sleeping => ProcessState::Debug(0), ProcessState::Debug(tids) => ProcessState::Debug(tids), + ProcessState::DebugIrq(tids) => ProcessState::DebugIrq(tids), ProcessState::Running(tids) => { // Switch to the parent process when we return. let current_tid = arch::process::current_tid(); @@ -2260,6 +2313,10 @@ impl SystemServices { }; { let process = self.get_process_mut(pid).unwrap(); + println!( + "Process {:?} went from {:?} to {:?}", + pid, process.state, new_process_state + ); // let old_state = process.state; process.state = new_process_state; // log_process_update(file!(), line!(), process, old_state); @@ -2269,9 +2326,9 @@ impl SystemServices { } #[cfg(feature = "gdb-stub")] - pub fn continue_process(&mut self, pid: PID) -> Result<(), xous_kernel::Error> { + pub fn resume_process_from_debug(&mut self, pid: PID) -> Result<(), xous_kernel::Error> { let process = self.get_process_mut(pid)?; - // let old_state = process.state; + let old_state = process.state; process.state = match process.state { ProcessState::Allocated => ProcessState::Allocated, ProcessState::Free => ProcessState::Free, @@ -2280,11 +2337,22 @@ impl SystemServices { ProcessState::Sleeping => ProcessState::Sleeping, ProcessState::Exception(x) => ProcessState::Exception(x), ProcessState::BlockedException(tids) => ProcessState::BlockedException(tids), + ProcessState::DebugIrq(tids) => ProcessState::Ready(tids), ProcessState::Debug(0) => ProcessState::Sleeping, ProcessState::Debug(tids) => ProcessState::Ready(tids), ProcessState::Running(tids) => ProcessState::Running(tids), }; - // log_process_update(file!(), line!(), process, old_state); + println!( + "Resuming process {:?} from debug, going from {:?} to {:?}", + pid, old_state, process.state + ); + + // Resume all interrupts that belong to this process + crate::irq::for_each_irq(|irq, irq_pid, _, _| { + if pid == *irq_pid { + crate::arch::irq::enable_irq(irq); + } + }); Ok(()) }