From bbda4365ae7d2a6e8079b114d21d93b53ffa48bc Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 1 Jun 2021 17:57:01 +0800 Subject: [PATCH] wip commit Signed-off-by: Sean Cross --- kernel/.cargo/config | 4 +- kernel/Cargo.lock | 51 +++++++++ kernel/Cargo.toml | 7 +- kernel/src/arch/riscv/irq.rs | 10 +- kernel/src/debug.rs | 208 ++++++++++++++++++++++++++++++++++- kernel/src/services.rs | 18 ++- kernel/src/syscall.rs | 5 + macros/src/lib.rs | 5 +- xous-rs/src/asm.S | 20 ++++ xous-rs/src/definitions.rs | 3 + xous-rs/src/syscall.rs | 6 +- 11 files changed, 308 insertions(+), 29 deletions(-) diff --git a/kernel/.cargo/config b/kernel/.cargo/config index bd2a78203..0274614de 100644 --- a/kernel/.cargo/config +++ b/kernel/.cargo/config @@ -19,5 +19,5 @@ rustflags = [ "-C", "force-frame-pointers=no", ] -#[build] -#target = "riscv32imac-unknown-none-elf" +[build] +target = "riscv32imac-unknown-none-elf" diff --git a/kernel/Cargo.lock b/kernel/Cargo.lock index 4c81f94ce..ffa4abbea 100644 --- a/kernel/Cargo.lock +++ b/kernel/Cargo.lock @@ -198,6 +198,25 @@ dependencies = [ "backtrace", ] +[[package]] +name = "gdbstub" +version = "0.5.0" +dependencies = [ + "cfg-if 0.1.10", + "log", + "managed", + "num-traits", + "paste", +] + +[[package]] +name = "gdbstub_arch" +version = "0.1.0" +dependencies = [ + "gdbstub", + "num-traits", +] + [[package]] name = "generic-array" version = "0.12.3" @@ -252,6 +271,8 @@ dependencies = [ "bitflags", "crossbeam-channel", "debug-here", + "gdbstub", + "gdbstub_arch", "hex", "lazy_static", "rand", @@ -274,6 +295,21 @@ version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2f02823cf78b754822df5f7f268fb59822e7296276d3e069d8e8cb26a14bd10" +[[package]] +name = "log" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" +dependencies = [ + "cfg-if 1.0.0", +] + +[[package]] +name = "managed" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d" + [[package]] name = "memchr" version = "2.3.3" @@ -289,6 +325,15 @@ dependencies = [ "adler", ] +[[package]] +name = "num-traits" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" +dependencies = [ + "autocfg", +] + [[package]] name = "object" version = "0.20.0" @@ -301,6 +346,12 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" +[[package]] +name = "paste" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acbf547ad0c65e31259204bd90935776d1c693cec2f4ff7abb7a1bbbd40dfe58" + [[package]] name = "ppv-lite86" version = "0.2.8" diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 1678c004a..1020114ac 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -7,6 +7,8 @@ version = "0.8.2" [dependencies] bitflags = "1.2.1" +gdbstub = {path = "../../gdbstub", optional = true, default_features = false} +gdbstub_arch = {path = "../../gdbstub/gdbstub_arch", optional = true} sha3 = {default-features = false, version = "0.8.2"} stats_alloc = {version = "0.1.8", optional = true} xous-kernel = {package = "xous", path = "../xous-rs", features = ["forget-memory-messages"]} @@ -19,11 +21,12 @@ riscv = "0.5.6" [features] debug-print = [] +gdbserver = ["gdbstub", "gdbstub_arch"] print-panics = [] report-memory = ["stats_alloc"] wrap-print = [] # default = ["print-panics", "debug-print", "wrap-print"] -default = ["print-panics"] +default = ["print-panics", "gdbserver"] [target.'cfg(any(windows, unix))'.dependencies] crossbeam-channel = "0.5" @@ -35,6 +38,6 @@ rand = "0.7" [profile.release] codegen-units = 1 # 1 better optimizations debug = true # symbols are nice and they don't increase the size on Flash -lto = "fat" +lto = "fat" # panic = "abort" # Remove some panic information # opt-level = 'z' # Optimize for size instead of performance diff --git a/kernel/src/arch/riscv/irq.rs b/kernel/src/arch/riscv/irq.rs index a32a958dd..38db3841f 100644 --- a/kernel/src/arch/riscv/irq.rs +++ b/kernel/src/arch/riscv/irq.rs @@ -104,15 +104,7 @@ pub extern "C" fn trap_handler( // println!("Syscall Result: {:?}", response); ArchProcess::with_current_mut(|p| { let thread = p.current_thread(); - // If we're resuming a process that was previously sleeping, restore the - // context. Otherwise, keep the context the same but pass the return - // values in 8 return registers. - if response == xous_kernel::Result::ResumeProcess { - crate::arch::syscall::resume(current_pid().get() == 1, thread); - } else { - // println!("Returning to address {:08x}", thread.sepc); - unsafe { _xous_syscall_return_result(&response, thread) }; - } + unsafe { _xous_syscall_return_result(&response, thread) }; }); } diff --git a/kernel/src/debug.rs b/kernel/src/debug.rs index 7d85a4c0b..2003cdea9 100644 --- a/kernel/src/debug.rs +++ b/kernel/src/debug.rs @@ -121,17 +121,195 @@ impl Uart { } } +#[cfg(all(feature = "gdbserver", baremetal))] +mod gdb_server { + use gdbstub::common::Tid; + use gdbstub::target::ext::base::multithread::{ + GdbInterrupt, MultiThreadOps, ResumeAction, ThreadStopReason, + }; + + use gdbstub::target::ext::base::BaseOps; + use gdbstub::target::{Target, TargetResult}; + use gdbstub::GdbStubStateMachine; + + pub struct XousTarget { + pid: Option, + tid: Option, + thread_mask: usize, + } + + pub static mut GDB_SERVER: Option<(GdbStubStateMachine, XousTarget)> = + None; + pub static mut GDB_BUFFER: [u8; 4096] = [0u8; 4096]; + + impl XousTarget { + pub fn new() -> XousTarget { + XousTarget { + pid: None, + tid: None, + thread_mask: 0, + } + } + } + + impl Target for XousTarget { + type Arch = gdbstub_arch::riscv::Riscv32; + type Error = &'static str; + fn base_ops(&mut self) -> BaseOps { + BaseOps::MultiThread(self) + } + } + + impl MultiThreadOps for XousTarget { + #[inline(never)] + fn resume( + &mut self, + default_resume_action: ResumeAction, + gdb_interrupt: GdbInterrupt<'_>, + ) -> Result, Self::Error> { + match default_resume_action { + ResumeAction::Step | ResumeAction::StepWithSignal(_) => { + Err("single-stepping not supported")? + } + _ => (), + } + + crate::services::SystemServices::with(|system_services| { + let current_pid = system_services.current_pid(); + + for process in &system_services.processes { + if !process.free() { + println!( + "PID {} {}:", + process.pid, + system_services.process_name(process.pid).unwrap_or("") + ); + process.activate().unwrap(); + crate::arch::mem::MemoryMapping::current().print_map(); + println!(); + } + } + system_services + .get_process(current_pid) + .unwrap() + .activate() + .unwrap(); + }); + Ok(ThreadStopReason::GdbInterrupt) + } + + #[inline(never)] + fn clear_resume_actions(&mut self) -> Result<(), Self::Error> { + Ok(()) + } + + #[inline(never)] + fn set_resume_action( + &mut self, + _tid: Tid, + _action: ResumeAction, + ) -> Result<(), Self::Error> { + Ok(()) + } + + #[inline(never)] + fn read_registers( + &mut self, + _regs: &mut gdbstub_arch::riscv::reg::RiscvCoreRegs, + _tid: Tid, + ) -> TargetResult<(), Self> { + Ok(()) + } + + #[inline(never)] + fn write_registers( + &mut self, + _regs: &gdbstub_arch::riscv::reg::RiscvCoreRegs, + _tid: Tid, + ) -> TargetResult<(), Self> { + Ok(()) + } + + #[inline(never)] + fn read_addrs( + &mut self, + _start_addr: u32, + data: &mut [u8], + _tid: Tid, // same address space for each core + ) -> TargetResult<(), Self> { + data.iter_mut().for_each(|b| *b = 0x55); + Ok(()) + } + + #[inline(never)] + fn write_addrs( + &mut self, + _start_addr: u32, + _data: &[u8], + _tid: Tid, // same address space for each core + ) -> TargetResult<(), Self> { + Ok(()) + } + + #[inline(never)] + fn list_active_threads( + &mut self, + register_thread: &mut dyn FnMut(Tid), + ) -> Result<(), Self::Error> { + // register_thread(Tid::new(1).unwrap()); + // register_thread(Tid::new(2).unwrap()); + Ok(()) + } + } +} + +#[cfg(all(feature = "gdbserver", baremetal))] +impl gdbstub::Connection for Uart { + type Error = (); + + fn read(&mut self) -> Result { + Err(()) + } + fn write(&mut self, byte: u8) -> Result<(), Self::Error> { + if unsafe { INITIALIZED != true } { + Err(())?; + } + let mut uart_csr = CSR::new(0xffcf_0000 as *mut u32); + // Wait until TXFULL is `0` + while uart_csr.r(utra::uart::TXFULL) != 0 { + () + } + uart_csr.wfo(utra::uart::RXTX_RXTX, byte as u32); + Ok(()) + } + fn peek(&mut self) -> Result, Self::Error> { + Ok(None) + } + fn flush(&mut self) -> Result<(), Self::Error> { + Ok(()) + } +} + #[cfg(all( not(test), baremetal, any(feature = "debug-print", feature = "print-panics") ))] pub fn irq(_irq_number: usize, _arg: *mut usize) { - let pressed_key = Uart {} + let b = Uart {} .getc() .expect("no character queued despite interrupt") as char; - println!("Interrupt {}: Key pressed: {}", _irq_number, pressed_key,); - match pressed_key { + + #[cfg(feature = "gdbserver")] + unsafe { + use crate::debug::gdb_server::GDB_SERVER; + if let Some((gdb, target)) = &mut GDB_SERVER.as_mut() { + gdb.pump(target, b as u8).unwrap(); + return; + } + } + + match b { 'm' => { println!("Printing memory page tables"); crate::services::SystemServices::with(|system_services| { @@ -201,13 +379,33 @@ pub fn irq(_irq_number: usize, _arg: *mut usize) { }); println!("{} k total", total_bytes / 1024); } + #[cfg(feature = "gdbserver")] + 'g' => { + use gdb_server::{XousTarget, GDB_BUFFER, GDB_SERVER}; + println!("Starting GDB server -- attach your debugger now"); + let xous_target = XousTarget::new(); + match gdbstub::GdbStubBuilder::new(Uart {}) + .with_packet_buffer(unsafe { &mut GDB_BUFFER }) + .build() + { + Ok(gdb) => match gdb.run_state_machine() { + Ok(gdb_state_machine) => unsafe { + GDB_SERVER = Some((gdb_state_machine, xous_target)) + }, + Err(e) => println!("Unable to start GDB state machine: {}", e), + }, + Err(e) => println!("Unable to start GDB server: {}", e), + } + } 'h' => { println!("Xous Kernel Debug"); println!("key | command"); println!("--- + -----------------------"); - println!(" r | report RAM usage of all processes"); - println!(" p | print all processes and threads"); + #[cfg(feature = "gdbserver")] + println!(" g | enter the gdb server"); println!(" m | print MMU page tables of all processes"); + println!(" p | print all processes and threads"); + println!(" r | report RAM usage of all processes"); } _ => {} } diff --git a/kernel/src/services.rs b/kernel/src/services.rs index a7bf79fb0..82f165861 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -52,8 +52,13 @@ pub enum ProcessState { Running(usize /* context bitmask */), /// This process is waiting for an event, such as as message or an - /// interrupt. There are no contexts that can be run. + /// interrupt. There are no contexts that can be run. This is + /// functionally equivalent to the invalid `Ready(0)` state. Sleeping, + + /// The process is currently being debugged. When it is resumed, + /// this will turn into `Ready(usize)` + Debug(usize), } impl core::fmt::Debug for ProcessState { @@ -65,6 +70,7 @@ 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), + Debug(rt) => write!(fmt, "Debug({:b})", rt), Sleeping => write!(fmt, "Sleeping"), } } @@ -510,7 +516,7 @@ impl SystemServices { let mut process = self.get_process_mut(pid)?; let available_threads = match process.state { ProcessState::Ready(x) | ProcessState::Running(x) => x, - ProcessState::Sleeping => 0, + ProcessState::Sleeping | ProcessState::Debug(_) => 0, ProcessState::Free => panic!("process was not allocated"), ProcessState::Setup(_) | ProcessState::Allocated => { panic!("process hasn't been set up yet") @@ -596,6 +602,7 @@ impl SystemServices { ProcessState::Free => return Err(xous_kernel::Error::ProcessNotFound), ProcessState::Sleeping => return Err(xous_kernel::Error::ProcessNotFound), ProcessState::Allocated => return Err(xous_kernel::Error::ProcessNotFound), + ProcessState::Debug(_) => return Err(xous_kernel::Error::DebugInProgress), ProcessState::Setup(setup) => { // Activate the process, which enables its memory mapping process.activate()?; @@ -862,9 +869,9 @@ impl SystemServices { new.current_thread = new_tid as _; } } - ProcessState::Sleeping => { - // println!("PID {} was sleeping", new_pid); - return Err(xous_kernel::Error::ProcessNotFound); + ProcessState::Sleeping | ProcessState::Debug(_) => { + // println!("PID {} was sleeping or being debugged", new_pid); + Err(xous_kernel::Error::ProcessNotFound)?; } } @@ -893,6 +900,7 @@ impl SystemServices { ProcessState::Running(x & !(1 << new_tid)) } ProcessState::Sleeping => ProcessState::Running(0), + ProcessState::Debug(_) => panic!("Process was being debugged"), }; new.activate()?; diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 3835dc07f..3dee1fa63 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -760,6 +760,11 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR unsafe { SWITCHTO_CALLER = None }; // TODO: Advance thread if cfg!(baremetal) { + ss.set_thread_result( + pid, + tid, + xous_kernel::Result::Ok, + ) ss.activate_process_thread(tid, ppid, 0, false) .map(|_| Ok(xous_kernel::Result::ResumeProcess)) .unwrap_or(Err(xous_kernel::Error::ProcessNotFound)) diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 665707142..d5482faf2 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -12,12 +12,9 @@ extern crate syn; use proc_macro2::Span; use rand::Rng; use rand::SeedableRng; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; use syn::{parse, spanned::Spanned, Ident, ItemFn, ReturnType, Type, Visibility}; -static CALL_COUNT: AtomicUsize = AtomicUsize::new(0); - use proc_macro::TokenStream; /// Attribute to declare the entry point of the program @@ -143,7 +140,7 @@ fn random_ident() -> Ident { .unwrap() .as_secs(); - let count: u64 = CALL_COUNT.fetch_add(1, Ordering::SeqCst) as u64; + let count = 1; let mut seed: [u8; 16] = [0; 16]; for (i, v) in seed.iter_mut().take(8).enumerate() { diff --git a/xous-rs/src/asm.S b/xous-rs/src/asm.S index 9843c9934..3b1c02a7b 100644 --- a/xous-rs/src/asm.S +++ b/xous-rs/src/asm.S @@ -18,3 +18,23 @@ _xous_syscall: sw a6, 6*REGBYTES(t0) sw a7, 7*REGBYTES(t0) ret + +.global aes_enc_round +aes_enc_round: + .word 0xb5050b // aes_enc_round a0, a1, a0 + ret + +.global aes_enc_round_last +aes_enc_round_last: + .word 0x4b5050b // aes_enc_round_last a0, a1, a0 + ret + +.global aes_dec_round +aes_dec_round: + .word 0x2b5050b // aes_dec_round a0, a1, a0 + ret + +.global aes_dec_round_last +aes_dec_round_last: + .word 0x6b5050b // aes_dec_round_last a0, a1, a0 + ret diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index ca66a55f1..8b86e9665 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -203,6 +203,7 @@ pub enum Error { AccessDenied = 23, UseBeforeInit = 24, DoubleFree = 25, + DebugInProgress = 26, } impl Error { @@ -234,6 +235,7 @@ impl Error { 23 => AccessDenied, 24 => UseBeforeInit, 25 => DoubleFree, + 26 => DebugInProgress, _ => UnknownError, } } @@ -265,6 +267,7 @@ impl Error { AccessDenied => 23, UseBeforeInit => 24, DoubleFree => 25, + DebugInProgress => 26, UnknownError => usize::MAX, } } diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 265fae7e6..86531c1b2 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -967,10 +967,12 @@ impl SysCall { /// Returns `true` if the given syscall may be called from an IRQ context pub fn can_call_from_interrupt(&self) -> bool { + if let SysCall::TrySendMessage(_cid, msg) = self { + return ! msg.is_blocking(); + } matches!( self, - SysCall::TrySendMessage(_, _) - | SysCall::TryConnect(_) + SysCall::TryConnect(_) | SysCall::TryReceiveMessage(_) | SysCall::ReturnToParent(_, _) | SysCall::ReturnScalar2(_, _, _)