openentropy_core/sources/frontier/
thread_lifecycle.rs1use std::thread;
4
5use crate::source::{EntropySource, SourceCategory, SourceInfo};
6use crate::sources::helpers::{extract_timing_entropy, mach_time};
7
8pub struct ThreadLifecycleSource;
33
34static THREAD_LIFECYCLE_INFO: SourceInfo = SourceInfo {
35 name: "thread_lifecycle",
36 description: "Thread create/join kernel scheduling and allocation jitter",
37 physics: "Creates and immediately joins threads, measuring the full lifecycle timing. \
38 Each cycle involves: Mach thread port allocation, zone allocator allocation, \
39 CPU core selection (P-core vs E-core), stack page allocation, TLS setup, and \
40 context switch on join. The scheduler\u{2019}s core selection depends on thermal \
41 state, load from ALL processes, and QoS priorities.",
42 category: SourceCategory::Frontier,
43 platform_requirements: &[],
44 entropy_rate_estimate: 3000.0,
45 composite: false,
46};
47
48impl EntropySource for ThreadLifecycleSource {
49 fn info(&self) -> &SourceInfo {
50 &THREAD_LIFECYCLE_INFO
51 }
52
53 fn is_available(&self) -> bool {
54 true
55 }
56
57 fn collect(&self, n_samples: usize) -> Vec<u8> {
58 let raw_count = n_samples * 4 + 64;
59 let mut timings: Vec<u64> = Vec::with_capacity(raw_count);
60 let mut lcg: u64 = mach_time() | 1;
61
62 for _ in 0..raw_count {
63 lcg = lcg.wrapping_mul(6364136223846793005).wrapping_add(1);
64 let work_amount = (lcg >> 48) as u32 % 100;
65
66 let t0 = mach_time();
67 let handle = thread::spawn(move || {
68 let mut sink: u64 = 0;
69 for j in 0..work_amount {
70 sink = sink.wrapping_add(j as u64);
71 }
72 std::hint::black_box(sink);
73 });
74 let _ = handle.join();
75 let t1 = mach_time();
76 timings.push(t1.wrapping_sub(t0));
77 }
78
79 extract_timing_entropy(&timings, n_samples)
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 #[test]
88 fn info() {
89 let src = ThreadLifecycleSource;
90 assert_eq!(src.name(), "thread_lifecycle");
91 assert_eq!(src.info().category, SourceCategory::Frontier);
92 assert!(!src.info().composite);
93 }
94
95 #[test]
96 #[ignore] fn collects_bytes() {
98 let src = ThreadLifecycleSource;
99 assert!(src.is_available());
100 let data = src.collect(64);
101 assert!(!data.is_empty());
102 assert!(data.len() <= 64);
103 if data.len() > 1 {
104 let first = data[0];
105 assert!(data.iter().any(|&b| b != first), "all bytes identical");
106 }
107 }
108}