From c9fd805da2ba241f4bc796e17f44b84b40bf608e Mon Sep 17 00:00:00 2001 From: yvt Date: Fri, 28 Apr 2023 00:35:02 +0900 Subject: [PATCH] fix(graphics-server): run `minifb` event loop on main thread Fixes crashes on macOS. Some operating systems and GUI frameworks, in particular Cocoa, don't allow creating an event loop from a thread other than the main thread (TID 1) and will abort a program on violation. --- .../graphics-server/src/backend/betrusted.rs | 12 +++- .../graphics-server/src/backend/minifb.rs | 57 ++++++++++++++++--- services/graphics-server/src/main.rs | 31 +++++----- 3 files changed, 77 insertions(+), 23 deletions(-) diff --git a/services/graphics-server/src/backend/betrusted.rs b/services/graphics-server/src/backend/betrusted.rs index 7b741c087..67fe6078b 100644 --- a/services/graphics-server/src/backend/betrusted.rs +++ b/services/graphics-server/src/backend/betrusted.rs @@ -10,6 +10,16 @@ pub const FB_LINES: usize = LINES as usize; pub const FB_SIZE: usize = FB_WIDTH_WORDS * FB_LINES; // 44 bytes by 536 lines const CONFIG_CLOCK_FREQUENCY: u32 = 100_000_000; +pub struct MainThreadToken(()); + +pub enum Never {} + +#[inline] +pub fn claim_main_thread(f: impl FnOnce(MainThreadToken) -> Never + Send + 'static) -> ! { + // Just call the closure - this backend will work on any thread + f(MainThreadToken(())) +} + pub struct XousDisplay { fb: MemoryRange, hwfb: MemoryRange, @@ -19,7 +29,7 @@ pub struct XousDisplay { } impl XousDisplay { - pub fn new() -> XousDisplay { + pub fn new(_main_thread_token: MainThreadToken) -> XousDisplay { let fb = xous::syscall::map_memory( None, None, diff --git a/services/graphics-server/src/backend/minifb.rs b/services/graphics-server/src/backend/minifb.rs index 426b9ace3..07453d64a 100644 --- a/services/graphics-server/src/backend/minifb.rs +++ b/services/graphics-server/src/backend/minifb.rs @@ -3,7 +3,7 @@ use crate::api::Point; use minifb::{Key, Window, WindowOptions}; use crate::api::{LINES, WIDTH}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, mpsc}; const HEIGHT: i16 = LINES; @@ -18,6 +18,48 @@ const MAX_FPS: u64 = 60; const DARK_COLOUR: u32 = 0xB5B5AD; const LIGHT_COLOUR: u32 = 0x1B1B19; +/// The channel for the backend to communicate back to the main thread that it +/// has claimed. +pub struct MainThreadToken(mpsc::SyncSender); + +/// A substitute for the native never type (`!`), which is still unstable on +/// `Fn` bounds. +pub enum Never {} + +/// Claim the calling thread (which must be a main thread) for use by the +/// backend and call the specified closure on a new thread. +pub fn claim_main_thread(f: impl FnOnce(MainThreadToken) -> Never + Send + 'static) -> ! { + // Some operating systems and GUI frameworks, in particular Cocoa, don't + // allow creating an event loop from a thread other than the main thread + // (TID 1) and will abort a program on violation (see issue #373), hence we + // need to claim the main thread for use by the backend. + let (send, recv) = mpsc::sync_channel(0); + + // Call the closure on a fake main thread + let fake_main_thread = std::thread::Builder::new() + .name("wrapped_main".into()) + .spawn(move || f(MainThreadToken(send))) + .unwrap(); + + // Process up to one request (that's the maximum because + // `MainThreadToken: !Clone`) + match recv.recv() { + Ok(thread_params) => { + // Run a GUI event loop. Abort if the fake main thread panics + thread_params.run_while(|| !fake_main_thread.is_finished()); + } + Err(mpsc::RecvError) => {} + } + + // Join on the fake main thread + match fake_main_thread.join() { + Ok(x) => match x {}, + // The default panic handler should have already outputted the panic + // message, so we can just call `abort` here + Err(_) => std::process::abort(), + } +} + pub struct XousDisplay { native_buffer: Arc>>, //[u32; WIDTH * HEIGHT], emulated_buffer: [u32; FB_SIZE], @@ -38,18 +80,15 @@ struct XousKeyboardHandler { } impl XousDisplay { - pub fn new() -> XousDisplay { + pub fn new(main_thread_token: MainThreadToken) -> XousDisplay { let native_buffer = vec![DARK_COLOUR; WIDTH as usize * HEIGHT as usize]; let native_buffer = Arc::new(Mutex::new(native_buffer)); - // Spawn a GUI thread + // Start a GUI event loop on the main thread let thread_params = MinifbThread { native_buffer: Arc::clone(&native_buffer), }; - std::thread::Builder::new() - .name("minifb".into()) - .spawn(move || thread_params.run()) - .unwrap(); + main_thread_token.0.send(thread_params).unwrap(); XousDisplay { native_buffer, @@ -126,7 +165,7 @@ impl XousDisplay { } impl MinifbThread { - pub fn run(self) -> ! { + pub fn run_while(self, mut predicate: impl FnMut() -> bool) { let mut window = Window::new( "Precursor", WIDTH as usize, @@ -159,7 +198,7 @@ impl MinifbThread { let mut native_buffer = Vec::new(); - loop { + while predicate() { // Copy the contents of `native_buffer`. Release the lock // immediately so as not to starve the server thread. native_buffer.clear(); diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index 9f9e53921..0daa71e2f 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -93,25 +93,30 @@ fn map_fonts() -> MemoryRange { fontregion } fn main () -> ! { - #[cfg(any(not(feature = "ditherpunk"), target_os = "macos"))] - wrapped_main(); + // Some operating systems and GUI frameworks don't allow creating an event + // loop from a thread other than TID 1. Let the backend claim this thread + // if this may be the case. + backend::claim_main_thread(move |main_thread_token| { + #[cfg(any(not(feature = "ditherpunk"), target_os = "macos"))] + wrapped_main(main_thread_token); - #[cfg(feature="ditherpunk")] - let stack_size = 1024 * 1024; - #[cfg(feature="ditherpunk")] - std::thread::Builder::new() - .stack_size(stack_size) - .spawn(wrapped_main) - .unwrap() - .join() - .unwrap() + #[cfg(feature="ditherpunk")] + let stack_size = 1024 * 1024; + #[cfg(feature="ditherpunk")] + std::thread::Builder::new() + .stack_size(stack_size) + .spawn(move || wrapped_main(main_thread_token)) + .unwrap() + .join() + .unwrap() + }) } -fn wrapped_main() -> ! { +fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! { log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); log::info!("my PID is {}", xous::process::id()); - let mut display = XousDisplay::new(); + let mut display = XousDisplay::new(main_thread_token); draw_boot_logo(&mut display); // bring this up as soon as possible let fontregion = map_fonts();