From 6ce7a6f0dc3e90f1398a65069fa30b13f1fe3ac4 Mon Sep 17 00:00:00 2001 From: Joey Beauvais-Feisthauer Date: Mon, 30 Sep 2024 11:29:14 -0400 Subject: [PATCH] Remove UB related to taking references to static muts --- ext/src/save.rs | 42 ++++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/ext/src/save.rs b/ext/src/save.rs index 5e82648df..34f14062c 100644 --- a/ext/src/save.rs +++ b/ext/src/save.rs @@ -3,7 +3,7 @@ use std::{ fs::File, io::{BufRead, BufReader, BufWriter, Error, ErrorKind, Read, Write}, path::{Path, PathBuf}, - sync::{Arc, Mutex}, + sync::{Arc, LazyLock, Mutex}, }; use algebra::Algebra; @@ -67,31 +67,25 @@ impl From> for SaveDirectory { } /// A DashSet> of files that are currently opened and being written to. When calling this -/// function for the first time, we set the ctrlc handler to delete currently opened files, then +/// function for the first time, we set the ctrlc handler to delete currently opened files then /// exit. fn open_files() -> &'static Mutex> { - use std::{mem::MaybeUninit, sync::Once}; - - static mut OPEN_FILES: MaybeUninit>> = MaybeUninit::uninit(); - static ONCE: Once = Once::new(); - unsafe { - ONCE.call_once(|| { - OPEN_FILES.write(Default::default()); - #[cfg(unix)] - ctrlc::set_handler(move || { - tracing::warn!("Ctrl-C detected. Deleting open files and exiting."); - let files = open_files().lock().unwrap(); - for file in &*files { - std::fs::remove_file(file) - .unwrap_or_else(|_| panic!("Error when deleting {file:?}")); - tracing::warn!("Deleted {}", file.to_string_lossy()); - } - std::process::exit(130); - }) - .expect("Error setting Ctrl-C handler"); - }); - OPEN_FILES.assume_init_ref() - } + static OPEN_FILES: LazyLock>> = LazyLock::new(|| { + #[cfg(unix)] + ctrlc::set_handler(move || { + tracing::warn!("Ctrl-C detected. Deleting open files and exiting."); + let files = open_files().lock().unwrap(); + for file in &*files { + std::fs::remove_file(file) + .unwrap_or_else(|_| panic!("Error when deleting {file:?}")); + tracing::warn!("Deleted {}", file.to_string_lossy()); + } + std::process::exit(130); + }) + .expect("Error setting Ctrl-C handler"); + Default::default() + }); + &OPEN_FILES } #[derive(Debug, Copy, Clone, Eq, PartialEq)]