From 8170d6219d7dd7fd22e7d38e2a5020950792bcbf Mon Sep 17 00:00:00 2001 From: Zhouqi Jiang Date: Sat, 5 Oct 2024 12:21:04 +0800 Subject: [PATCH] [rust] resolve deadlock on multiple Stdin/Stdout references Use &'static Mutex type other than MutexGuard for Stdin/Stdout inner field Signed-off-by: Zhouqi Jiang --- board/100ask-d1-h-rs/src/main.rs | 4 ++-- rust/src/stdio.rs | 21 ++++++++++----------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/board/100ask-d1-h-rs/src/main.rs b/board/100ask-d1-h-rs/src/main.rs index 4de7696a..c186cf0b 100644 --- a/board/100ask-d1-h-rs/src/main.rs +++ b/board/100ask-d1-h-rs/src/main.rs @@ -63,8 +63,8 @@ fn main(p: Peripherals, _c: Clocks) { } } -fn command_bootargs<'a>(cli: &mut CliHandle<'a, Stdout, Infallible>) { - ufmt::uwrite!(cli.writer(), "TODO Bootargs").ok(); +fn command_bootargs<'a>(_cli: &mut CliHandle<'a, Stdout, Infallible>) { + println!("TODO Bootargs"); } fn command_reload<'a>(cli: &mut CliHandle<'a, Stdout, Infallible>) { diff --git a/rust/src/stdio.rs b/rust/src/stdio.rs index ca1242fe..d092b24a 100644 --- a/rust/src/stdio.rs +++ b/rust/src/stdio.rs @@ -36,7 +36,7 @@ pub fn _print(args: core::fmt::Arguments) { /// A handle to the global standard output stream of the current runtime. pub struct Stdout { - inner: spin::MutexGuard<'static, Option>, + inner: &'static spin::Mutex>, } impl embedded_io::ErrorType for Stdout { @@ -46,14 +46,16 @@ impl embedded_io::ErrorType for Stdout { impl embedded_io::Write for Stdout { #[inline] fn write(&mut self, buf: &[u8]) -> Result { - if let Some(stdout) = &mut *self.inner { + let mut lock = self.inner.lock(); + if let Some(stdout) = &mut *lock { stdout.inner.write_all(buf).ok(); } Ok(buf.len()) } #[inline] fn flush(&mut self) -> Result<(), Self::Error> { - if let Some(stdout) = &mut *self.inner { + let mut lock = self.inner.lock(); + if let Some(stdout) = &mut *lock { stdout.inner.flush().ok(); } Ok(()) @@ -62,7 +64,7 @@ impl embedded_io::Write for Stdout { /// A handle to the standard input stream of a runtime. pub struct Stdin { - inner: spin::MutexGuard<'static, Option>, + inner: &'static spin::Mutex>, } impl embedded_io::ErrorType for Stdin { @@ -72,7 +74,8 @@ impl embedded_io::ErrorType for Stdin { impl embedded_io::Read for Stdin { #[inline] fn read(&mut self, buf: &mut [u8]) -> Result { - if let Some(stdin) = &mut *self.inner { + let mut lock = self.inner.lock(); + if let Some(stdin) = &mut *lock { stdin.inner.read(buf).ok(); } Ok(buf.len()) @@ -82,15 +85,11 @@ impl embedded_io::Read for Stdin { /// Constructs a new handle to the standard output of the current environment. #[inline] pub fn stdout() -> Stdout { - Stdout { - inner: STDOUT.lock(), - } + Stdout { inner: &STDOUT } } /// Constructs a new handle to the standard input of the current environment. #[inline] pub fn stdin() -> Stdin { - Stdin { - inner: STDIN.lock(), - } + Stdin { inner: &STDIN } }