subc-os 0.1.36

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Handle-pinned process observations and spawn-time executable identity on Windows.
#![allow(unsafe_code)]

use std::{
    fs::File,
    io,
    mem::size_of,
    os::windows::{
        fs::OpenOptionsExt,
        io::{AsRawHandle, FromRawHandle, OwnedHandle},
    },
    path::{Path, PathBuf},
    time::Duration,
};
use windows_sys::Win32::{
    Foundation::{
        ERROR_INVALID_PARAMETER, FILETIME, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
        WAIT_TIMEOUT,
    },
    Storage::FileSystem::{
        FileAttributeTagInfo, GetFileInformationByHandleEx, FILE_ATTRIBUTE_REPARSE_POINT,
        FILE_ATTRIBUTE_TAG_INFO, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ, FILE_SHARE_WRITE,
    },
    System::{
        Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
            TH32CS_SNAPPROCESS,
        },
        ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS},
        Threading::{
            GetProcessTimes, OpenProcess, TerminateProcess, WaitForSingleObject,
            PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
        },
    },
};

use crate::retained_file_identity as identity;
use crate::{MemoryKind, Observation, Process, ResourceUsage};

/// A Windows file object identity, not a content hash. All sixteen ID bytes matter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WindowsFileIdentity {
    pub volume_serial_number: u64,
    pub file_id: [u8; 16],
}

/// A resolved executable held against rename or deletion until the suspended spawn binds it.
#[derive(Debug)]
pub struct ExecutableCapture {
    file: File,
    path: PathBuf,
    identity: WindowsFileIdentity,
}

/// Identity of a suspended child, retaining the exact process handle used at spawn.
#[derive(Debug)]
pub struct SpawnedImage {
    process: Process,
    path: PathBuf,
    start_time: u64,
    identity: WindowsFileIdentity,
}

impl PartialEq for SpawnedImage {
    fn eq(&self, other: &Self) -> bool {
        self.process.pid() == other.process.pid()
            && self.start_time == other.start_time
            && self.identity == other.identity
            && self.path == other.path
    }
}
impl Eq for SpawnedImage {}

/// Why the running image cannot be confirmed. Unknown identity is never agreement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageUnavailable {
    ProcessExited,
    ProcessIdentityUnconfirmed,
    SpawnPathUnreadable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageAgreement {
    Match(WindowsFileIdentity),
    Mismatch {
        running: WindowsFileIdentity,
        disk: WindowsFileIdentity,
    },
    Unavailable(ImageUnavailable),
}

fn open_image(path: &Path) -> io::Result<File> {
    let file = std::fs::OpenOptions::new()
        .read(true)
        // Omitting FILE_SHARE_DELETE pins the name across CreateProcessW.
        .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
        .open(path)?;
    let mut attributes: FILE_ATTRIBUTE_TAG_INFO = Default::default();
    // SAFETY: file owns a live handle; the output buffer has the requested layout and size.
    if unsafe {
        GetFileInformationByHandleEx(
            file.as_raw_handle(),
            FileAttributeTagInfo,
            (&mut attributes as *mut FILE_ATTRIBUTE_TAG_INFO).cast(),
            size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    if attributes.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "executable is a reparse point",
        ));
    }
    Ok(file)
}

impl ExecutableCapture {
    /// Open the resolved spawn path before CreateProcessW. The caller must use
    /// `path()` for the suspended spawn, then bind before resuming the child.
    pub fn open(path: &Path) -> io::Result<Self> {
        // Reject the supplied leaf before canonicalizing: canonicalize would hide
        // a symlink or other leaf reparse point by resolving its target.
        let supplied = open_image(path)?;
        let path = std::fs::canonicalize(path)?;
        let file = open_image(&path)?;
        let identity = identity(&file)?;
        if identity != self::identity(&supplied)? {
            return Err(io::Error::other(
                "executable changed while resolving its path",
            ));
        }
        Ok(Self {
            file,
            path,
            identity,
        })
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Bind while the child is suspended. `child` must be the handle returned by
    /// the spawn, not a process reopened by PID. The file lock is released only
    /// after the child's handle and creation time have been retained.
    pub fn bind(self, child: &std::process::Child) -> io::Result<SpawnedImage> {
        let handle = child.as_raw_handle();
        // SAFETY: AsRawHandle borrows a live child process handle for this call.
        let borrowed = unsafe { std::os::windows::io::BorrowedHandle::borrow_raw(handle) };
        self.bind_owned(child.id(), borrowed.try_clone_to_owned()?)
    }

    /// Bind a Tokio child while it is suspended, retaining its spawn handle.
    #[cfg(feature = "tokio")]
    pub fn bind_tokio(self, child: &tokio::process::Child) -> io::Result<SpawnedImage> {
        let pid = child
            .id()
            .ok_or_else(|| io::Error::other("child already reaped"))?;
        let handle = child
            .raw_handle()
            .ok_or_else(|| io::Error::other("child handle unavailable"))?;
        // SAFETY: raw_handle borrows the unreaped Tokio child's live process handle.
        let borrowed = unsafe { std::os::windows::io::BorrowedHandle::borrow_raw(handle) };
        self.bind_owned(pid, borrowed.try_clone_to_owned()?)
    }

    fn bind_owned(self, pid: u32, handle: OwnedHandle) -> io::Result<SpawnedImage> {
        let process = Process { pid, handle };
        let start_time = observe(&process)
            .ok_or_else(|| io::Error::other("spawned process identity unavailable"))?
            .start_time;
        // Keep the executable locked until the identity is bound to the process.
        drop(self.file);
        Ok(SpawnedImage {
            process,
            path: self.path,
            start_time,
            identity: self.identity,
        })
    }
}

impl SpawnedImage {
    pub fn process(&self) -> &Process {
        &self.process
    }
    pub fn start_time(&self) -> u64 {
        self.start_time
    }
    pub fn identity(&self) -> WindowsFileIdentity {
        self.identity
    }
    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn agreement(&self, expected_start_time: u64) -> ImageAgreement {
        if expected_start_time != self.start_time {
            return ImageAgreement::Unavailable(ImageUnavailable::ProcessIdentityUnconfirmed);
        }
        if !matches!(observe(&self.process), Some(observed) if observed.start_time == self.start_time)
        {
            return self.unavailable_process();
        }
        let disk = match open_image(&self.path).and_then(|file| identity(&file)) {
            Ok(identity) => identity,
            Err(_) => return ImageAgreement::Unavailable(ImageUnavailable::SpawnPathUnreadable),
        };
        // Check again on the pinned process handle: IDs may be reused after exit,
        // so a disk observation made as the child exited must not be compared.
        if !matches!(observe(&self.process), Some(observed) if observed.start_time == self.start_time)
        {
            return self.unavailable_process();
        }
        if disk == self.identity {
            ImageAgreement::Match(self.identity)
        } else {
            ImageAgreement::Mismatch {
                running: self.identity,
                disk,
            }
        }
    }

    fn unavailable_process(&self) -> ImageAgreement {
        ImageAgreement::Unavailable(if matches!(wait(&self.process, Duration::ZERO), Ok(true)) {
            ImageUnavailable::ProcessExited
        } else {
            ImageUnavailable::ProcessIdentityUnconfirmed
        })
    }
}

pub(crate) fn open(pid: u32) -> io::Result<Option<OwnedHandle>> {
    // SAFETY: OpenProcess takes a numeric pid and returns an owned handle or null.
    let handle = unsafe {
        OpenProcess(
            PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE | PROCESS_TERMINATE,
            0,
            pid,
        )
    };
    if handle.is_null() {
        let error = io::Error::last_os_error();
        if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
            return Ok(None);
        }
        return Err(error);
    }
    // SAFETY: successful OpenProcess transfers ownership of this handle.
    Ok(Some(unsafe { OwnedHandle::from_raw_handle(handle) }))
}

fn times(handle: HANDLE) -> Option<(u64, u64, u64)> {
    let (mut creation, mut exit, mut kernel, mut user): (FILETIME, FILETIME, FILETIME, FILETIME) =
        Default::default();
    // SAFETY: the caller holds a live process handle; all output buffers are valid FILETIMEs.
    if unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) } == 0 {
        return None;
    }
    let ticks =
        |time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
    Some((ticks(creation), ticks(kernel), ticks(user)))
}

pub(crate) fn cumulative_cpu_ms(process: &Process) -> Option<u64> {
    let (_, kernel, user) = times(process.handle.as_raw_handle())?;
    Some(kernel.saturating_add(user) / 10_000)
}

impl std::os::windows::io::AsRawHandle for Process {
    fn as_raw_handle(&self) -> std::os::windows::io::RawHandle {
        self.handle.as_raw_handle()
    }
}

pub(crate) fn parent_pid(pid: u32) -> Option<u32> {
    // Query-only handles also work for ancestors we may not terminate. Holding
    // the child handle prevents its pid from being reused during the snapshot.
    let query = |pid| {
        // SAFETY: OpenProcess accepts a numeric pid and returns an owned handle.
        let raw = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
        if raw.is_null() {
            None
        } else {
            // SAFETY: successful OpenProcess transfers ownership of this handle.
            Some(unsafe { OwnedHandle::from_raw_handle(raw) })
        }
    };
    let child = query(pid)?;
    let child_time = times(child.as_raw_handle())?.0;
    // SAFETY: no pointers are passed; a successful snapshot is an owned handle.
    let raw = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
    if raw == INVALID_HANDLE_VALUE {
        return None;
    }
    // SAFETY: the successful snapshot transfers ownership of this handle.
    let snapshot = unsafe { OwnedHandle::from_raw_handle(raw) };
    // SAFETY: PROCESSENTRY32W is a C output structure with valid zero values.
    let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
    entry.dwSize = size_of::<PROCESSENTRY32W>() as u32;
    // SAFETY: the snapshot is live and entry has the required size and alignment.
    let mut found = unsafe { Process32FirstW(snapshot.as_raw_handle(), &mut entry) };
    while found != 0 {
        if entry.th32ProcessID == pid {
            let parent = query(entry.th32ParentProcessID)?;
            let parent_time = times(parent.as_raw_handle())?.0;
            return older_parent(entry.th32ParentProcessID, parent_time, child_time);
        }
        // SAFETY: the snapshot and the initialized entry remain valid.
        found = unsafe { Process32NextW(snapshot.as_raw_handle(), &mut entry) };
    }
    None
}

fn older_parent(parent: u32, parent_time: u64, child_time: u64) -> Option<u32> {
    (parent_time <= child_time).then_some(parent)
}

#[test]
fn a_parent_created_after_its_child_is_a_reused_pid() {
    assert_eq!(older_parent(42, 101, 100), None);
    assert_eq!(older_parent(42, 100, 100), Some(42));
    assert_eq!(older_parent(42, 99, 100), Some(42));
}

pub(crate) fn wait(process: &Process, timeout: Duration) -> io::Result<bool> {
    let millis = u32::try_from(timeout.as_millis())
        .unwrap_or(u32::MAX - 1)
        .min(u32::MAX - 1);
    // SAFETY: the owned process handle stays live throughout the wait.
    let result = match unsafe { WaitForSingleObject(process.handle.as_raw_handle(), millis) } {
        WAIT_OBJECT_0 => Ok(true),
        WAIT_TIMEOUT => Ok(false),
        _ => Err(io::Error::last_os_error()),
    };
    #[cfg(test)]
    if !timeout.is_zero() && matches!(result, Ok(true)) {
        // TerminateProcess can finish before a test's next observation. Record
        // the actual bounded wait too, so removing it cannot pass by scheduling luck.
        COMPLETED_BOUNDED_WAITS.with(|count| count.set(count.get() + 1));
    }
    result
}

#[cfg(test)]
thread_local! {
    static COMPLETED_BOUNDED_WAITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
pub(crate) fn completed_bounded_waits() -> u64 {
    COMPLETED_BOUNDED_WAITS.with(|count| count.get())
}

pub(crate) fn observe(process: &Process) -> Option<Observation> {
    if wait(process, Duration::ZERO).ok()? {
        return None;
    }
    let start_time = times(process.handle.as_raw_handle())?.0;
    if wait(process, Duration::ZERO).ok()? {
        return None;
    }
    Some(Observation {
        start_time,
        executable: None,
    })
}

pub(crate) fn force_stop(process: &Process, expected: u64, timeout: Duration) -> io::Result<bool> {
    let Some(observed) = observe(process) else {
        return if wait(process, Duration::ZERO)? {
            Ok(true)
        } else {
            Err(io::Error::other("process identity unavailable"))
        };
    };
    if observed.start_time != expected {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "process creation time does not match",
        ));
    }
    // SAFETY: the checked process is the same owned handle, never reopened by PID.
    if unsafe { TerminateProcess(process.handle.as_raw_handle(), 1) } == 0 {
        let error = io::Error::last_os_error();
        if !wait(process, Duration::ZERO)? {
            return Err(error);
        }
    }
    wait(process, timeout)
}

pub(crate) fn terminate_with_exit_code(process: &Process, exit_code: u32) -> io::Result<bool> {
    if wait(process, Duration::ZERO)? {
        return Ok(false);
    }
    // SAFETY: the retained process handle remains owned throughout this call.
    if unsafe { TerminateProcess(process.handle.as_raw_handle(), exit_code) } == 0 {
        let error = io::Error::last_os_error();
        if wait(process, Duration::ZERO)? {
            return Ok(false);
        }
        return Err(error);
    }
    Ok(true)
}

pub(crate) fn resource_usage(process: &Process) -> Option<ResourceUsage> {
    observe(process)?;
    let mut counters: PROCESS_MEMORY_COUNTERS = Default::default();
    // SAFETY: the process handle is live and the output buffer has the requested layout and size.
    if unsafe {
        GetProcessMemoryInfo(
            process.handle.as_raw_handle(),
            &mut counters,
            size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
        )
    } == 0
    {
        return None;
    }
    let (_, kernel, user) = times(process.handle.as_raw_handle())?;
    observe(process)?;
    let duration = |ticks: u64| {
        Duration::from_secs(ticks / 10_000_000) + Duration::from_nanos((ticks % 10_000_000) * 100)
    };
    Some(ResourceUsage {
        memory_bytes: counters.WorkingSetSize as u64,
        memory_kind: MemoryKind::WindowsWorkingSet,
        swap_bytes: None,
        cpu_user: duration(user),
        cpu_system: duration(kernel),
    })
}

mod process_snapshot;
pub(crate) use process_snapshot::process_entries;