//! The self-check's program written against Rust's std rather than `rt`: //! that std works on Pinnacle — its heap, threads, locks, channels, //! thread-locals, clocks and randomness. It prints what it found and exits //! 0, or panics (which aborts with a nonzero code). use std::cell::Cell; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, RwLock, mpsc}; use std::thread; use std::time::{Duration, Instant, SystemTime}; const THREADS: usize = 8; const INCREMENTS: u64 = 10_000; thread_local! { static COUNT: Cell = const { Cell::new(0) }; static DROPPED: Dropped = const { Dropped }; } /// Counts, as it is dropped, a thread's thread-locals going with it. struct Dropped; static DROPS: AtomicUsize = AtomicUsize::new(0); impl Drop for Dropped { fn drop(&mut self) { DROPS.fetch_add(1, Ordering::SeqCst); } } fn main() { // Started by itself as a child ([`processes`]). if std::env::args().nth(1).as_deref() == Some("child") { child(); } // The heap, and a HashMap, whose keys are seeded from the kernel's // randomness. let mut map = HashMap::new(); for i in 0..10_000u64 { map.insert(i, i.to_string()); } assert_eq!(map[&9_999], "9999"); let big = vec![7u8; 8 << 20]; assert!(big.iter().all(|&b| b == 7)); drop(big); // The main thread's stack grows past its first 64 KiB. let deep = std::hint::black_box([3u8; 512 << 10]); assert_eq!(deep.iter().map(|&b| b as usize).sum::(), 3 * (512 << 10)); // Freed memory goes back: 2 GiB taken and freed 32 MiB at a time fits // in a machine of 256 MiB only if each block is given back. for round in 0..64u8 { let block = vec![round; 32 << 20]; assert_eq!(block[(32 << 20) - 1], round); } // Threads contending for one mutex, across the cores; each with its own // thread-locals, whose destructors run as it ends. let total = Arc::new(Mutex::new(0u64)); let workers: Vec<_> = (0..THREADS) .map(|_| { let total = total.clone(); thread::spawn(move || { DROPPED.with(|_| {}); for _ in 0..INCREMENTS { *total.lock().unwrap() += 1; COUNT.with(|c| c.set(c.get() + 1)); } COUNT.with(Cell::get) }) }) .collect(); for worker in workers { assert_eq!(worker.join().unwrap(), INCREMENTS, "a thread-local was shared"); } assert_eq!(*total.lock().unwrap(), THREADS as u64 * INCREMENTS, "increments were lost"); assert_eq!(COUNT.with(Cell::get), 0, "the main thread's thread-local changed"); assert_eq!(DROPS.load(Ordering::SeqCst), THREADS, "thread-locals were not dropped"); // A condition variable: two threads taking turns. let turn = Arc::new((Mutex::new(0u32), Condvar::new())); let other = { let turn = turn.clone(); thread::spawn(move || { let (lock, cv) = &*turn; for round in 0..100 { let mut t = cv.wait_while(lock.lock().unwrap(), |t| *t != round * 2 + 1).unwrap(); *t += 1; cv.notify_one(); } }) }; { let (lock, cv) = &*turn; for round in 0..100 { let mut t = cv.wait_while(lock.lock().unwrap(), |t| *t != round * 2).unwrap(); *t += 1; cv.notify_one(); } } other.join().unwrap(); assert_eq!(*turn.0.lock().unwrap(), 200); // A channel from several senders, and a reader-writer lock. let (tx, rx) = mpsc::channel(); let shared = Arc::new(RwLock::new(vec![1u64, 2, 3])); for i in 0..4u64 { let (tx, shared) = (tx.clone(), shared.clone()); thread::spawn(move || { let sum: u64 = shared.read().unwrap().iter().sum(); tx.send(i * 100 + sum).unwrap(); }); } drop(tx); let mut got: Vec = rx.iter().collect(); got.sort(); assert_eq!(got, [6, 106, 206, 306]); shared.write().unwrap().push(4); assert_eq!(shared.read().unwrap().len(), 4); // Clocks: a sleep lasts at least as long as asked, a timed wait times // out, and the time of day is past 2020 when the board has a clock. let start = Instant::now(); thread::sleep(Duration::from_millis(30)); let slept = start.elapsed(); assert!(slept >= Duration::from_millis(30), "slept only {slept:?}"); let pair = Mutex::new(()); let (_guard, timeout) = Condvar::new() .wait_timeout(pair.lock().unwrap(), Duration::from_millis(20)) .unwrap(); assert!(timeout.timed_out(), "a timed wait did not time out"); let since_epoch = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); let cores = thread::available_parallelism().map_or(0, |n| n.get()); assert!(cores >= 1); println!( "std: a main stack of 512 KiB; 2 GiB allocated and given back; {THREADS} threads, {} locked increments, condvar, channel, rwlock; slept {} ms; {cores} cores; {} s since 1970", THREADS as u64 * INCREMENTS, slept.as_millis(), since_epoch.as_secs(), ); let written = files(); let fetched = network(); println!("std: files ({written} bytes written, read back, listed, renamed, removed); network ({fetched} bytes over TCP)"); processes(); println!("std: a child process given arguments, an environment and pipes, its exit code collected"); } /// std::process: this program started again as a child, with an argument, /// a variable and its three streams piped; what it writes and how it ends /// come back. fn processes() { use std::io::Write; use std::process::{Command, Stdio}; let mut child = Command::new("std-check") .arg("child") .env("GREETING", "hoi") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .unwrap(); child.stdin.take().unwrap().write_all(b"hello from the parent").unwrap(); let output = child.wait_with_output().unwrap(); assert_eq!(String::from_utf8_lossy(&output.stdout), "HELLO FROM THE PARENT"); assert_eq!(String::from_utf8_lossy(&output.stderr), "hoi"); assert_eq!(output.status.code(), Some(7), "the child ended with {}", output.status); assert!(Command::new("no-such-program").status().is_err()); } /// As the child: its stdin in capitals to stdout, the variable to stderr, /// then exit 7. fn child() -> ! { use std::io::{Read, Write}; let mut input = String::new(); std::io::stdin().read_to_string(&mut input).unwrap(); std::io::stdout().write_all(input.to_uppercase().as_bytes()).unwrap(); let greeting = std::env::var("GREETING").unwrap(); std::io::stderr().write_all(greeting.as_bytes()).unwrap(); std::process::exit(7) } /// std::fs on the system disk: a folder, a file written, appended to, read /// back from a position, listed, renamed, and all of it removed. Returns the /// bytes written. fn files() -> u64 { use std::fs; use std::io::{Read, Seek, SeekFrom, Write}; let dir = "/std-check"; let _ = fs::remove_dir_all(dir); fs::create_dir(dir).unwrap(); assert!(fs::create_dir(dir).is_err(), "a folder was made twice"); let path = format!("{dir}/notes.txt"); let mut file = fs::File::create(&path).unwrap(); file.write_all(b"Hello from std, ").unwrap(); drop(file); let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap(); file.write_all(b"on Pinnacle.").unwrap(); drop(file); assert_eq!(fs::read_to_string(&path).unwrap(), "Hello from std, on Pinnacle."); let mut file = fs::File::open(&path).unwrap(); file.seek(SeekFrom::Start(16)).unwrap(); let mut rest = String::new(); file.read_to_string(&mut rest).unwrap(); assert_eq!(rest, "on Pinnacle."); let big: Vec = (0..300_000u32).map(|i| (i % 251) as u8).collect(); fs::write(format!("{dir}/big.bin"), &big).unwrap(); assert_eq!(fs::read(format!("{dir}/big.bin")).unwrap(), big); assert_eq!(fs::metadata(&path).unwrap().len(), 28); assert!(fs::metadata(dir).unwrap().is_dir()); let mut names: Vec = fs::read_dir(dir) .unwrap() .map(|e| e.unwrap().file_name().into_string().unwrap()) .collect(); names.sort(); assert_eq!(names, ["big.bin", "notes.txt"]); fs::rename(&path, format!("{dir}/renamed.txt")).unwrap(); assert!(!fs::exists(&path).unwrap()); assert_eq!(fs::read_to_string(format!("{dir}/renamed.txt")).unwrap(), "Hello from std, on Pinnacle."); assert_eq!( fs::File::open(format!("{dir}/missing")).unwrap_err().kind(), std::io::ErrorKind::NotFound ); fs::remove_dir_all(dir).unwrap(); assert!(!fs::exists(dir).unwrap()); 28 + big.len() as u64 } /// std::net: once the network has an address, fetch the package source's /// catalog (its address from the Store's setting, read with std::fs) over a /// TcpStream, as HTTP. Returns the bytes received. fn network() -> usize { use std::io::{Read, Write}; use std::net::{TcpStream, UdpSocket}; // A board without a network has no sockets: nothing to fetch. let Ok(probe) = UdpSocket::bind("0.0.0.0:0") else { return 0; }; let start = Instant::now(); while probe.local_addr().unwrap().ip().is_unspecified() { assert!(start.elapsed() < Duration::from_secs(20), "the network got no address"); thread::sleep(Duration::from_millis(50)); } let url = std::fs::read_to_string("/settings/store-url").unwrap(); let host = url.trim().trim_start_matches("http://").trim_end_matches('/'); let mut stream = TcpStream::connect(host).unwrap(); stream.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); write!(stream, "GET /catalog HTTP/1.0\r\nHost: {host}\r\n\r\n").unwrap(); let mut response = Vec::new(); stream.read_to_end(&mut response).unwrap(); let text = String::from_utf8_lossy(&response); assert!(text.starts_with("HTTP/1."), "not an HTTP answer: {text:.40}"); assert!(text.contains(" 200 "), "the catalog was not served: {text:.40}"); response.len() }