Add isolated time broker and raw Windows capture with Linux evidence
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,343 @@
|
||||
//! Fixed, temporary SCM capture probe. It never installs a service or opens an
|
||||
//! RMM store, key/pin, network endpoint, W32Time, job or clock setter.
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod probe {
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_agent_windows::{helper_ipc as ipc, signed_clock};
|
||||
use rmm_domain::jobs::hash;
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
fs::OpenOptions,
|
||||
io::Write,
|
||||
mem::{size_of, zeroed},
|
||||
os::windows::{
|
||||
fs::OpenOptionsExt,
|
||||
io::{AsRawHandle, FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
sync::{
|
||||
OnceLock,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
Security::*,
|
||||
Storage::FileSystem::*,
|
||||
System::{Services::*, Threading::*},
|
||||
};
|
||||
const BASE: &str = r"C:\ProgramData\RustDiscoverySignedClockCapture";
|
||||
const LS: &str = "RmmSignedClockCaptureLocalService";
|
||||
const SYSTEM: &str = "RmmSignedClockCaptureSystem";
|
||||
static CASE: OnceLock<uuid::Uuid> = OnceLock::new();
|
||||
static ROLE: OnceLock<Role> = OnceLock::new();
|
||||
static STATUS: AtomicUsize = AtomicUsize::new(0);
|
||||
static STAGE: AtomicUsize = AtomicUsize::new(0);
|
||||
#[derive(Clone, Copy)]
|
||||
enum Role {
|
||||
LocalService,
|
||||
System,
|
||||
}
|
||||
impl Role {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::LocalService => LS,
|
||||
Self::System => SYSTEM,
|
||||
}
|
||||
}
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::LocalService => "local-service",
|
||||
Self::System => "system",
|
||||
}
|
||||
}
|
||||
fn user(self) -> &'static str {
|
||||
match self {
|
||||
Self::LocalService => "S-1-5-19",
|
||||
Self::System => "S-1-5-18",
|
||||
}
|
||||
}
|
||||
}
|
||||
fn wide(value: &str) -> Vec<u16> {
|
||||
value.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
fn owned(value: HANDLE) -> Result<OwnedHandle> {
|
||||
ensure!(
|
||||
!value.is_null() && value != INVALID_HANDLE_VALUE,
|
||||
"CAPTURE_NATIVE_HANDLE"
|
||||
);
|
||||
// SAFETY: only uniquely owned handles returned by successful APIs enter.
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(value) })
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct TokenReport {
|
||||
user_sid: &'static str,
|
||||
service_sid_sha256: String,
|
||||
elevation_flag: u32,
|
||||
elevation_type: i32,
|
||||
}
|
||||
fn token(role: Role) -> Result<TokenReport> {
|
||||
let mut thread = ptr::null_mut();
|
||||
// SAFETY: valid output pointer, query only, no impersonation is created.
|
||||
if unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut thread) } != 0 {
|
||||
let _thread = owned(thread)?;
|
||||
anyhow::bail!("CAPTURE_IMPERSONATION_FORBIDDEN");
|
||||
}
|
||||
ensure!(
|
||||
unsafe { GetLastError() } == ERROR_NO_TOKEN,
|
||||
"CAPTURE_THREAD_TOKEN"
|
||||
);
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw) } != 0,
|
||||
"CAPTURE_PROCESS_TOKEN"
|
||||
);
|
||||
let handle = owned(raw)?;
|
||||
let sid = ipc::service_sid(role.name())?;
|
||||
ipc::verify_token(handle.as_raw_handle(), role.user(), &sid)?;
|
||||
let mut elevation: TOKEN_ELEVATION = unsafe { zeroed() };
|
||||
let mut count = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetTokenInformation(
|
||||
handle.as_raw_handle(),
|
||||
TokenElevation,
|
||||
ptr::addr_of_mut!(elevation).cast(),
|
||||
size_of::<TOKEN_ELEVATION>() as u32,
|
||||
&mut count,
|
||||
)
|
||||
} != 0
|
||||
&& count as usize == size_of::<TOKEN_ELEVATION>(),
|
||||
"CAPTURE_ELEVATION"
|
||||
);
|
||||
let mut kind: TOKEN_ELEVATION_TYPE = 0;
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetTokenInformation(
|
||||
handle.as_raw_handle(),
|
||||
TokenElevationType,
|
||||
ptr::addr_of_mut!(kind).cast(),
|
||||
size_of::<TOKEN_ELEVATION_TYPE>() as u32,
|
||||
&mut count,
|
||||
)
|
||||
} != 0
|
||||
&& count as usize == size_of::<TOKEN_ELEVATION_TYPE>()
|
||||
&& (1..=3).contains(&kind),
|
||||
"CAPTURE_ELEVATION_TYPE"
|
||||
);
|
||||
Ok(TokenReport {
|
||||
user_sid: role.user(),
|
||||
service_sid_sha256: hash(sid.as_bytes()),
|
||||
elevation_flag: elevation.TokenIsElevated,
|
||||
elevation_type: kind,
|
||||
})
|
||||
}
|
||||
fn create(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
ensure!(bytes.len() <= 16384, "CAPTURE_REPORT_LIMIT");
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0
|
||||
&& info.dwFileAttributes
|
||||
& (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
== 0
|
||||
&& info.nNumberOfLinks == 1,
|
||||
"CAPTURE_NEW_FILE_IDENTITY"
|
||||
);
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
fn execute() -> Result<()> {
|
||||
let role = *ROLE.get().context("CAPTURE_ROLE")?;
|
||||
let case = *CASE.get().context("CAPTURE_CASE")?;
|
||||
STAGE.store(10, Ordering::SeqCst);
|
||||
let token = token(role)?;
|
||||
let role_sid = ipc::service_sid(role.name())?;
|
||||
// Both fixed fixture SIDs may read the common case directory. Only the
|
||||
// selected fixture SID may write its own role subdirectory.
|
||||
let readers = vec![ipc::service_sid(LS)?, ipc::service_sid(SYSTEM)?];
|
||||
let root = PathBuf::from(BASE);
|
||||
let case_root = root.join(case.to_string());
|
||||
let output = case_root.join(role.tag());
|
||||
let image_path = case_root.join("SignedClockCapture.exe");
|
||||
ensure!(
|
||||
std::env::current_exe()? == image_path,
|
||||
"CAPTURE_FIXED_IMAGE_PATH"
|
||||
);
|
||||
let mut held = vec![
|
||||
ipc::PinnedFile::open(&root, true, &readers, &[], false)?,
|
||||
ipc::PinnedFile::open(&case_root, true, &readers, &[], false)?,
|
||||
ipc::PinnedFile::open(&output, true, &readers, &[role_sid], false)?,
|
||||
];
|
||||
let mut image = ipc::PinnedFile::open(&image_path, false, &readers, &[], false)?;
|
||||
let image_sha256 = image.sha256()?;
|
||||
let image_file = image.identity;
|
||||
held.push(image);
|
||||
for name in ["intent.json", "report.json", "end.json"] {
|
||||
ensure!(!output.join(name).exists(), "CAPTURE_CASE_ALREADY_ENTERED");
|
||||
}
|
||||
let pid = unsafe { GetCurrentProcessId() };
|
||||
let (mut born, mut ended, mut kernel, mut user) = (
|
||||
unsafe { zeroed() },
|
||||
unsafe { zeroed() },
|
||||
unsafe { zeroed() },
|
||||
unsafe { zeroed() },
|
||||
);
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetProcessTimes(
|
||||
GetCurrentProcess(),
|
||||
&mut born,
|
||||
&mut ended,
|
||||
&mut kernel,
|
||||
&mut user,
|
||||
)
|
||||
} != 0,
|
||||
"CAPTURE_PROCESS_BIRTH"
|
||||
);
|
||||
let born = (u64::from(born.dwHighDateTime) << 32) | u64::from(born.dwLowDateTime);
|
||||
STAGE.store(20, Ordering::SeqCst);
|
||||
// Fixed existing read-only CIM boot getter, BEFORE the 250ms sampling
|
||||
// budget; never a caller script or a substitute process-start identity.
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
let boot = uuid::Uuid::parse_str(&runtime.block_on(rmm_agent_windows::native::boot_id())?)?;
|
||||
ensure!(
|
||||
!boot.is_nil() && born > 0 && pid > 0,
|
||||
"CAPTURE_NATIVE_IDENTITY"
|
||||
);
|
||||
create(
|
||||
&output.join("intent.json"),
|
||||
&serde_json::to_vec(
|
||||
&serde_json::json!({"schema_version":1,"case_id":case,"role":role.tag(),"pid":pid,"process_birth_filetime":born,"image_sha256":image_sha256,"boot_id":boot,"calibrated":false,"clock_authority":false,"no_repeat":true,"maximum_samples":128,"maximum_capture_ns":250000000}),
|
||||
)?,
|
||||
)?;
|
||||
STAGE.store(30, Ordering::SeqCst);
|
||||
let result = (|| {
|
||||
let captures = signed_clock::diagnostic_capture_series()?;
|
||||
STAGE.store(40, Ordering::SeqCst);
|
||||
let current_token = token_role_recheck(role, &token)?;
|
||||
for file in &mut held {
|
||||
file.check()?;
|
||||
}
|
||||
let report = serde_json::to_vec(
|
||||
&serde_json::json!({"schema_version":1,"case_id":case,"role":role.tag(),"calibrated":false,"clock_authority":false,"read_only_clock":true,"token":current_token,"pid":pid,"process_birth_filetime":born,"image_sha256":image_sha256,"image_file":image_file,"boot_id":boot,"capture":captures}),
|
||||
)?;
|
||||
ensure!(report.len() <= 16384, "CAPTURE_REPORT_LIMIT");
|
||||
create(&output.join("report.json"), &report)?;
|
||||
Ok::<_, anyhow::Error>(hash(&report))
|
||||
})();
|
||||
let end = serde_json::to_vec(
|
||||
&serde_json::json!({"schema_version":1,"case_id":case,"role":role.tag(),"success":result.is_ok(),"stage":STAGE.load(Ordering::SeqCst),"report_sha256":result.as_ref().ok(),"calibrated":false,"clock_authority":false,"no_repeat":true}),
|
||||
)?;
|
||||
create(&output.join("end.json"), &end)?;
|
||||
result?;
|
||||
STAGE.store(50, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
fn token_role_recheck(role: Role, original: &TokenReport) -> Result<TokenReport> {
|
||||
let current = token(role)?;
|
||||
ensure!(
|
||||
serde_json::to_vec(¤t)? == serde_json::to_vec(original)?,
|
||||
"CAPTURE_TOKEN_CHANGED"
|
||||
);
|
||||
Ok(current)
|
||||
}
|
||||
fn status(state: u32, error: u32) {
|
||||
let handle = STATUS.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
let value = SERVICE_STATUS {
|
||||
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
|
||||
dwCurrentState: state,
|
||||
dwControlsAccepted: 0,
|
||||
dwWin32ExitCode: error,
|
||||
dwServiceSpecificExitCode: if error == 1066 {
|
||||
STAGE.load(Ordering::SeqCst) as u32
|
||||
} else {
|
||||
0
|
||||
},
|
||||
dwCheckPoint: 0,
|
||||
dwWaitHint: 10000,
|
||||
};
|
||||
// SAFETY: this handle is returned by SCM for this own temporary service.
|
||||
unsafe { SetServiceStatus(handle, &value) };
|
||||
}
|
||||
unsafe extern "system" fn control(
|
||||
_: u32,
|
||||
_: u32,
|
||||
_: *mut std::ffi::c_void,
|
||||
_: *mut std::ffi::c_void,
|
||||
) -> u32 {
|
||||
0
|
||||
}
|
||||
unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
|
||||
let Some(role) = ROLE.get().copied() else {
|
||||
return;
|
||||
};
|
||||
let name = wide(role.name());
|
||||
let handle =
|
||||
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
STATUS.store(handle as usize, Ordering::SeqCst);
|
||||
status(SERVICE_RUNNING, 0);
|
||||
let result = execute();
|
||||
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
||||
}
|
||||
pub fn dispatch() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
ensure!(
|
||||
args.len() == 4 && args[1] == "--service",
|
||||
"CAPTURE_FIXED_ARGUMENTS"
|
||||
);
|
||||
let case = uuid::Uuid::parse_str(&args[2])?;
|
||||
ensure!(
|
||||
case.get_version_num() == 4 && case.to_string() == args[2],
|
||||
"CAPTURE_CANONICAL_UUID"
|
||||
);
|
||||
let role = match args[3].as_str() {
|
||||
"local-service" => Role::LocalService,
|
||||
"system" => Role::System,
|
||||
_ => anyhow::bail!("CAPTURE_FIXED_ROLE"),
|
||||
};
|
||||
CASE.set(case)
|
||||
.map_err(|_| anyhow::anyhow!("CAPTURE_ALREADY_DISPATCHED"))?;
|
||||
ROLE.set(role)
|
||||
.map_err(|_| anyhow::anyhow!("CAPTURE_ALREADY_DISPATCHED"))?;
|
||||
let mut name = wide(role.name());
|
||||
let table = [
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: name.as_mut_ptr(),
|
||||
lpServiceProc: Some(service_main),
|
||||
},
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: ptr::null_mut(),
|
||||
lpServiceProc: None,
|
||||
},
|
||||
];
|
||||
ensure!(
|
||||
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
|
||||
"CAPTURE_SCM_ONLY"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
probe::dispatch()
|
||||
}
|
||||
#[cfg(not(all(windows, feature = "system-helper")))]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
anyhow::bail!("Windows system-helper build required; no diagnostic clock fallback")
|
||||
}
|
||||
@@ -148,18 +148,13 @@ fn bracket_sample(
|
||||
base_error_ns > 0 && base_error_ns <= MAX_BASE_ERROR_NS,
|
||||
"TIME_NATIVE_CALIBRATION_REQUIRED"
|
||||
);
|
||||
let width = interrupt_after
|
||||
.checked_sub(interrupt_before)
|
||||
.and_then(|value| value.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
|
||||
let unbiased_width = unbiased_after
|
||||
.checked_sub(unbiased_before)
|
||||
.and_then(|value| value.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
|
||||
ensure!(
|
||||
width.abs_diff(unbiased_width) <= SECOND_NS,
|
||||
"TIME_NATIVE_CAPTURE_SUSPEND"
|
||||
);
|
||||
let width = raw_widths(
|
||||
interrupt_before,
|
||||
interrupt_after,
|
||||
unbiased_before,
|
||||
unbiased_after,
|
||||
)?
|
||||
.0;
|
||||
let capture_error_ns = width
|
||||
.checked_add(base_error_ns)
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_OVERFLOW"))?;
|
||||
@@ -184,6 +179,215 @@ fn bracket_sample(
|
||||
})
|
||||
}
|
||||
|
||||
fn raw_widths(ib: u64, ia: u64, ub: u64, ua: u64) -> Result<(u64, u64)> {
|
||||
let width = ia
|
||||
.checked_sub(ib)
|
||||
.and_then(|value| value.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
|
||||
let unbiased_width = ua
|
||||
.checked_sub(ub)
|
||||
.and_then(|value| value.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_NATIVE_CAPTURE_COUNTER"))?;
|
||||
ensure!(
|
||||
width.abs_diff(unbiased_width) <= SECOND_NS,
|
||||
"TIME_NATIVE_CAPTURE_SUSPEND"
|
||||
);
|
||||
Ok((width, unbiased_width))
|
||||
}
|
||||
/// Private raw capture, not a Sample and never clock authority.
|
||||
#[derive(Clone, Copy)]
|
||||
struct RawCapture {
|
||||
wall: u64,
|
||||
ib: u64,
|
||||
ub: u64,
|
||||
ua: u64,
|
||||
ia: u64,
|
||||
}
|
||||
impl RawCapture {
|
||||
fn widths(self) -> Result<(u64, u64)> {
|
||||
ensure!(
|
||||
self.wall > 116_444_736_000_000_000 && self.ib > 0 && self.ub > 0,
|
||||
"TIME_NATIVE_RAW_RANGE"
|
||||
);
|
||||
raw_widths(self.ib, self.ia, self.ub, self.ua)
|
||||
}
|
||||
fn row(self) -> [u64; 5] {
|
||||
[self.wall, self.ib, self.ub, self.ua, self.ia]
|
||||
}
|
||||
}
|
||||
/// Fixed read-only getter sequence shared by installed and diagnostic paths.
|
||||
#[cfg(windows)]
|
||||
fn raw_capture() -> Result<RawCapture> {
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GetSystemTimePreciseAsFileTime(value: *mut u64);
|
||||
fn QueryInterruptTimePrecise(value: *mut u64);
|
||||
fn QueryUnbiasedInterruptTimePrecise(value: *mut u64);
|
||||
}
|
||||
let mut value = RawCapture {
|
||||
wall: 0,
|
||||
ib: 0,
|
||||
ub: 0,
|
||||
ua: 0,
|
||||
ia: 0,
|
||||
};
|
||||
// SAFETY: documented VOID getters write valid aligned u64 outputs. These
|
||||
// Windows10+ imports have no optional fallback or caller-selected target.
|
||||
unsafe {
|
||||
QueryInterruptTimePrecise(&mut value.ib);
|
||||
QueryUnbiasedInterruptTimePrecise(&mut value.ub);
|
||||
GetSystemTimePreciseAsFileTime(&mut value.wall);
|
||||
QueryUnbiasedInterruptTimePrecise(&mut value.ua);
|
||||
QueryInterruptTimePrecise(&mut value.ia);
|
||||
}
|
||||
value.widths()?;
|
||||
Ok(value)
|
||||
}
|
||||
const RAW_SAMPLES: usize = 128;
|
||||
const RAW_BUDGET_NS: u64 = 250_000_000;
|
||||
/// Numeric observations only. No Deserialize, calibrated Sample conversion or
|
||||
/// readiness flag; a report cannot open SignedClock or bypass its pin loader.
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct CaptureDiagnostics {
|
||||
schema_version: u32,
|
||||
calibrated: bool,
|
||||
clock_authority: bool,
|
||||
columns_100ns: [&'static str; 5],
|
||||
samples_100ns: Vec<[u64; 5]>,
|
||||
sample_count: u32,
|
||||
elapsed_monotonic_ns: u64,
|
||||
elapsed_interrupt_ns: u64,
|
||||
max_bracket_ns: u64,
|
||||
max_internal_interrupt_unbiased_difference_ns: u64,
|
||||
max_wall_interrupt_difference_ns: u64,
|
||||
max_interrupt_unbiased_difference_ns: u64,
|
||||
}
|
||||
struct RawSeries {
|
||||
first: Option<RawCapture>,
|
||||
previous: Option<RawCapture>,
|
||||
rows: Vec<[u64; 5]>,
|
||||
max_bracket_ns: u64,
|
||||
max_internal_delta_ns: u64,
|
||||
max_wall_delta_ns: u64,
|
||||
max_unbiased_delta_ns: u64,
|
||||
}
|
||||
impl RawSeries {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
first: None,
|
||||
previous: None,
|
||||
rows: Vec::with_capacity(RAW_SAMPLES),
|
||||
max_bracket_ns: 0,
|
||||
max_internal_delta_ns: 0,
|
||||
max_wall_delta_ns: 0,
|
||||
max_unbiased_delta_ns: 0,
|
||||
}
|
||||
}
|
||||
fn push(&mut self, value: RawCapture) -> Result<()> {
|
||||
ensure!(self.rows.len() < RAW_SAMPLES, "TIME_RAW_SAMPLE_LIMIT");
|
||||
let (width, unbiased_width) = value.widths()?;
|
||||
ensure!(width <= RAW_BUDGET_NS, "TIME_RAW_CAPTURE_BUDGET");
|
||||
if let Some(previous) = self.previous {
|
||||
let wall = value
|
||||
.wall
|
||||
.checked_sub(previous.wall)
|
||||
.and_then(|v| v.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_WALL_BACKWARD"))?;
|
||||
let interrupt = value
|
||||
.ia
|
||||
.checked_sub(previous.ia)
|
||||
.and_then(|v| v.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_INTERRUPT_BACKWARD"))?;
|
||||
let unbiased = value
|
||||
.ua
|
||||
.checked_sub(previous.ua)
|
||||
.and_then(|v| v.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_UNBIASED_BACKWARD"))?;
|
||||
ensure!(
|
||||
value.ib >= previous.ia && value.ub >= previous.ua,
|
||||
"TIME_RAW_COUNTER_ORDER"
|
||||
);
|
||||
self.max_wall_delta_ns = self.max_wall_delta_ns.max(wall.abs_diff(interrupt));
|
||||
self.max_unbiased_delta_ns =
|
||||
self.max_unbiased_delta_ns.max(interrupt.abs_diff(unbiased));
|
||||
ensure!(
|
||||
wall.abs_diff(interrupt) <= SECOND_NS && interrupt.abs_diff(unbiased) <= SECOND_NS,
|
||||
"TIME_RAW_DISCONTINUITY"
|
||||
);
|
||||
}
|
||||
self.first.get_or_insert(value);
|
||||
self.previous = Some(value);
|
||||
self.max_bracket_ns = self.max_bracket_ns.max(width);
|
||||
self.max_internal_delta_ns = self
|
||||
.max_internal_delta_ns
|
||||
.max(width.abs_diff(unbiased_width));
|
||||
self.rows.push(value.row());
|
||||
Ok(())
|
||||
}
|
||||
fn finish(self, elapsed_monotonic_ns: u64) -> Result<CaptureDiagnostics> {
|
||||
ensure!(
|
||||
self.rows.len() == RAW_SAMPLES && elapsed_monotonic_ns <= RAW_BUDGET_NS,
|
||||
"TIME_RAW_INCOMPLETE_OR_EXPIRED"
|
||||
);
|
||||
let first = self
|
||||
.first
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_EMPTY"))?;
|
||||
let last = self
|
||||
.previous
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_EMPTY"))?;
|
||||
let elapsed_interrupt_ns = last
|
||||
.ia
|
||||
.checked_sub(first.ib)
|
||||
.and_then(|v| v.checked_mul(100))
|
||||
.ok_or_else(|| anyhow::anyhow!("TIME_RAW_COUNTER_RANGE"))?;
|
||||
ensure!(
|
||||
elapsed_interrupt_ns <= RAW_BUDGET_NS,
|
||||
"TIME_RAW_INTERRUPT_BUDGET"
|
||||
);
|
||||
Ok(CaptureDiagnostics {
|
||||
schema_version: 1,
|
||||
calibrated: false,
|
||||
clock_authority: false,
|
||||
columns_100ns: [
|
||||
"wall_filetime",
|
||||
"interrupt_before",
|
||||
"unbiased_before",
|
||||
"unbiased_after",
|
||||
"interrupt_after",
|
||||
],
|
||||
samples_100ns: self.rows,
|
||||
sample_count: RAW_SAMPLES as u32,
|
||||
elapsed_monotonic_ns,
|
||||
elapsed_interrupt_ns,
|
||||
max_bracket_ns: self.max_bracket_ns,
|
||||
max_internal_interrupt_unbiased_difference_ns: self.max_internal_delta_ns,
|
||||
max_wall_interrupt_difference_ns: self.max_wall_delta_ns,
|
||||
max_interrupt_unbiased_difference_ns: self.max_unbiased_delta_ns,
|
||||
})
|
||||
}
|
||||
}
|
||||
/// Exactly128 bounded captures, spaced at fixed1ms target offsets. A missed
|
||||
/// 250ms own-monotonic budget aborts; no sleep/time-setting API is used.
|
||||
#[cfg(windows)]
|
||||
pub fn diagnostic_capture_series() -> Result<CaptureDiagnostics> {
|
||||
let started = std::time::Instant::now();
|
||||
let budget = std::time::Duration::from_nanos(RAW_BUDGET_NS);
|
||||
let mut series = RawSeries::new();
|
||||
for index in 0..RAW_SAMPLES {
|
||||
let due = std::time::Duration::from_millis(index as u64);
|
||||
loop {
|
||||
let elapsed = started.elapsed();
|
||||
ensure!(elapsed <= budget, "TIME_RAW_MONOTONIC_BUDGET");
|
||||
if elapsed >= due {
|
||||
break;
|
||||
}
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
series.push(raw_capture()?)?;
|
||||
}
|
||||
series.finish(started.elapsed().as_nanos().try_into()?)
|
||||
}
|
||||
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
mod installed {
|
||||
use super::*;
|
||||
@@ -239,24 +443,10 @@ mod installed {
|
||||
PROCESS.get_or_init(|| Mutex::new(Continuity::default()))
|
||||
}
|
||||
fn capture(base_error_ns: u64) -> Result<Sample> {
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GetSystemTimePreciseAsFileTime(value: *mut u64);
|
||||
fn QueryInterruptTimePrecise(value: *mut u64);
|
||||
fn QueryUnbiasedInterruptTimePrecise(value: *mut u64);
|
||||
}
|
||||
let (mut ib, mut ia, mut ub, mut ua, mut wall) = (0, 0, 0, 0, 0);
|
||||
// SAFETY: documented VOID kernel getters with valid aligned u64
|
||||
// outputs. Windows 10+ is required; no optional API fallback exists.
|
||||
unsafe {
|
||||
QueryInterruptTimePrecise(&mut ib);
|
||||
QueryUnbiasedInterruptTimePrecise(&mut ub);
|
||||
GetSystemTimePreciseAsFileTime(&mut wall);
|
||||
QueryUnbiasedInterruptTimePrecise(&mut ua);
|
||||
QueryInterruptTimePrecise(&mut ia);
|
||||
}
|
||||
bracket_sample(wall, ib, ia, ub, ua, base_error_ns)
|
||||
let raw = raw_capture()?;
|
||||
bracket_sample(raw.wall, raw.ib, raw.ia, raw.ub, raw.ua, base_error_ns)
|
||||
}
|
||||
|
||||
fn observed(boot: Uuid, base_error_ns: u64) -> Result<(Sample, u64)> {
|
||||
let mut state = process()
|
||||
.lock()
|
||||
@@ -560,6 +750,63 @@ mod tests {
|
||||
capture_error_ns: 1_000_000,
|
||||
}
|
||||
}
|
||||
fn raw(index: u64) -> RawCapture {
|
||||
RawCapture {
|
||||
wall: 134_444_736_000_000_000 + index * 10_000,
|
||||
ib: 10_000_000 + index * 10_000,
|
||||
ia: 10_000_010 + index * 10_000,
|
||||
ub: 9_000_000 + index * 10_000,
|
||||
ua: 9_000_008 + index * 10_000,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn raw_capture_denies_backward_wall_counters_and_incomplete_or_expired_series() {
|
||||
let mut series = RawSeries::new();
|
||||
series.push(raw(0)).unwrap();
|
||||
assert!(
|
||||
series
|
||||
.push(RawCapture {
|
||||
wall: raw(0).wall - 1,
|
||||
..raw(1)
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
let mut series = RawSeries::new();
|
||||
series.push(raw(0)).unwrap();
|
||||
assert!(
|
||||
series
|
||||
.push(RawCapture {
|
||||
ia: raw(0).ia - 1,
|
||||
ib: raw(0).ib - 1,
|
||||
..raw(1)
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
assert!(RawSeries::new().finish(0).is_err());
|
||||
let mut series = RawSeries::new();
|
||||
for index in 0..RAW_SAMPLES as u64 {
|
||||
series.push(raw(index)).unwrap();
|
||||
}
|
||||
assert!(series.finish(RAW_BUDGET_NS + 1).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn complete_raw_report_is_bounded_non_authoritative_and_keeps_actual_brackets() {
|
||||
let mut series = RawSeries::new();
|
||||
for index in 0..RAW_SAMPLES as u64 {
|
||||
series.push(raw(index)).unwrap();
|
||||
}
|
||||
assert!(series.push(raw(RAW_SAMPLES as u64)).is_err());
|
||||
let report = series.finish(128_000_000).unwrap();
|
||||
assert_eq!(report.sample_count, 128);
|
||||
assert_eq!(report.max_bracket_ns, 1000);
|
||||
assert_eq!(report.elapsed_interrupt_ns, 127_001_000);
|
||||
assert_eq!(report.max_internal_interrupt_unbiased_difference_ns, 200);
|
||||
let value = serde_json::to_value(&report).unwrap();
|
||||
assert_eq!(value["calibrated"], false);
|
||||
assert_eq!(value["clock_authority"], false);
|
||||
assert!(value.get("capture_error_ns").is_none());
|
||||
assert!(serde_json::to_vec(&report).unwrap().len() < 16384);
|
||||
}
|
||||
#[test]
|
||||
fn job_key_cannot_be_reintroduced_as_a_time_key_with_different_hex_case() {
|
||||
assert_eq!(
|
||||
|
||||
Reference in New Issue
Block a user