subc-os 0.1.61

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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Suspended module creation with protected discretionary access control lists
//! (DACLs) for the process and its primary thread.

#![allow(unsafe_code)]

mod environment;
mod wait;

pub use environment::Environment;

use environment::wide_without_nul;
use std::{
    ffi::OsStr,
    future::poll_fn,
    io,
    mem::{size_of, size_of_val},
    os::windows::{
        io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle, RawHandle},
        process::ExitStatusExt,
    },
    path::{Path, PathBuf},
    process::ExitStatus,
    ptr::{null, null_mut},
    task::Poll,
};
use wait::ProcessWait;
use windows_sys::Win32::{
    Foundation::{
        DuplicateHandle, DUPLICATE_SAME_ACCESS, ERROR_ACCESS_DENIED, GENERIC_READ,
        INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT,
    },
    Security::SECURITY_ATTRIBUTES,
    Storage::FileSystem::{CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING},
    System::{
        Pipes::CreatePipe,
        Threading::{
            CreateProcessW, DeleteProcThreadAttributeList, GetCurrentProcess, GetExitCodeProcess,
            InitializeProcThreadAttributeList, ResumeThread, TerminateProcess,
            UpdateProcThreadAttribute, WaitForSingleObject, CREATE_NO_WINDOW, CREATE_SUSPENDED,
            CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT, PROCESS_INFORMATION,
            PROC_THREAD_ATTRIBUTE_HANDLE_LIST, STARTF_USESTDHANDLES, STARTUPINFOEXW,
        },
    },
};

/// A Windows child whose creation handles let the supervisor assign, resume,
/// wait and terminate without reopening the protected process or thread.
#[derive(Debug)]
pub struct Child {
    // Drop the wait registration before closing its process handle.
    wait: Option<ProcessWait>,
    process: OwnedHandle,
    primary_thread: Option<OwnedHandle>,
    pid: u32,
    exit: Option<ExitStatus>,
    kill_on_drop: bool,
    stdout: Option<OwnedHandle>,
    stderr: Option<OwnedHandle>,
}

impl Child {
    /// The PID while the child has not been reaped.
    pub fn id(&self) -> Option<u32> {
        self.exit.is_none().then_some(self.pid)
    }

    /// The unreaped process's creation handle, not a handle reopened by PID.
    pub fn process_handle(&self) -> Option<BorrowedHandle<'_>> {
        self.id().map(|_| self.process.as_handle())
    }

    /// Take the parent end of the synchronous stdout pipe.
    pub fn take_stdout(&mut self) -> Option<OwnedHandle> {
        self.stdout.take()
    }

    /// Take the parent end of the synchronous stderr pipe.
    pub fn take_stderr(&mut self) -> Option<OwnedHandle> {
        self.stderr.take()
    }

    /// Start execution and close the primary-thread handle on success.
    pub fn resume(&mut self) -> io::Result<()> {
        let thread = self
            .primary_thread
            .as_ref()
            .ok_or_else(|| io::Error::other("child already resumed"))?;
        // SAFETY: CreateProcessW supplied this live creator handle with full
        // access. Reopening by thread ID would be denied THREAD_SUSPEND_RESUME.
        if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
            return Err(io::Error::last_os_error());
        }
        self.primary_thread = None;
        Ok(())
    }

    /// Leave termination to another owner if this child is dropped after resume.
    pub fn disarm_kill_on_drop(&mut self) {
        assert!(
            self.primary_thread.is_none(),
            "cannot disarm a suspended child"
        );
        self.kill_on_drop = false;
    }

    /// Check for exit without blocking, recording the exit status if signalled.
    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
        if self.exit.is_some() {
            return Ok(self.exit);
        }
        let handle = self.process.as_raw_handle();
        // SAFETY: The process handle stays live throughout both queries.
        match unsafe { WaitForSingleObject(handle, 0) } {
            WAIT_OBJECT_0 => {
                let mut code = 0;
                // SAFETY: code points to a writable DWORD and the process has exited.
                if unsafe { GetExitCodeProcess(handle, &mut code) } == 0 {
                    return Err(io::Error::last_os_error());
                }
                self.wait = None;
                self.exit = Some(ExitStatus::from_raw(code));
                Ok(self.exit)
            }
            WAIT_TIMEOUT => Ok(None),
            _ => Err(io::Error::last_os_error()),
        }
    }

    /// Wait asynchronously for exit without dedicating a thread to this child.
    pub async fn wait(&mut self) -> io::Result<ExitStatus> {
        poll_fn(|cx| {
            if let Some(status) = self.try_wait()? {
                return Poll::Ready(Ok(status));
            }
            let registration = match &self.wait {
                Some(wait) => wait,
                None => self
                    .wait
                    .insert(ProcessWait::new(self.process.as_raw_handle())?),
            };
            match registration.poll(cx) {
                Poll::Pending => Poll::Pending,
                Poll::Ready(()) => Poll::Ready(
                    self.try_wait()?
                        .ok_or_else(|| io::Error::other("process wait callback fired before exit")),
                ),
            }
        })
        .await
    }

    /// Request termination; use `wait` or `try_wait` to reap.
    pub fn start_kill(&mut self) -> io::Result<()> {
        if self.exit.is_some() {
            return Ok(());
        }
        // SAFETY: The process handle is live and has termination access.
        if unsafe { TerminateProcess(self.process.as_raw_handle(), 1) } != 0 {
            return Ok(());
        }
        let error = io::Error::last_os_error();
        // Windows also reports access denied when the process already exited.
        if error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) && self.try_wait()?.is_some() {
            return Ok(());
        }
        Err(error)
    }
}

impl Drop for Child {
    fn drop(&mut self) {
        if self.kill_on_drop {
            let _ = self.start_kill();
        }
    }
}

/// Report the native thread ID from a fixture's entry point.
#[cfg(feature = "test-support")]
pub fn current_thread_id_for_test() -> u32 {
    // SAFETY: GetCurrentThreadId takes no arguments and returns a value.
    unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }
}

/// Create an executable image (see `resolve_program`) suspended with restricted
/// process and thread DACLs. Only stdin (NUL), stdout and stderr handles are
/// inherited by the child.
pub fn spawn<'a>(
    program: &Path,
    args: impl IntoIterator<Item = &'a OsStr>,
    environment: &Environment,
    current_dir: &Path,
) -> io::Result<Child> {
    let program = std::path::absolute(resolve_program(program)?)?;
    let mut command_line = command_line(program.as_os_str(), args)?;
    let mut application = wide_without_nul(program.as_os_str())?;
    application.push(0);
    let mut directory = wide_without_nul(std::path::absolute(current_dir)?.as_os_str())?;
    directory.push(0);

    let _inheritance = crate::child_spawn::windows_inheritance_lock();
    let (stdout, out_write) = output_pipe()?;
    let (stderr, err_write) = output_pipe()?;
    let stdin = null_input()?;
    let handles = [
        stdin.as_raw_handle(),
        out_write.as_raw_handle(),
        err_write.as_raw_handle(),
    ];
    let mut attributes = Attributes::new(&handles)?;
    let mut startup = STARTUPINFOEXW::default();
    startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
    startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
    [
        startup.StartupInfo.hStdInput,
        startup.StartupInfo.hStdOutput,
        startup.StartupInfo.hStdError,
    ] = handles;
    startup.lpAttributeList = attributes.as_mut_ptr();
    let mut info = PROCESS_INFORMATION::default();

    crate::windows_acl::with_child_security(|process, thread| {
        // SAFETY: The descriptors, attribute list, stdio handles and terminated
        // strings stay live through the call; only command_line and info are
        // output buffers. bInheritHandles enables the explicit stdio list, not
        // the non-inheritable process and thread handles returned to the creator.
        if unsafe {
            CreateProcessW(
                application.as_ptr(),
                command_line.as_mut_ptr(),
                process,
                thread,
                1,
                CREATE_SUSPENDED
                    | CREATE_NO_WINDOW
                    | CREATE_UNICODE_ENVIRONMENT
                    | EXTENDED_STARTUPINFO_PRESENT,
                environment.0.as_ptr().cast(),
                directory.as_ptr(),
                &startup.StartupInfo,
                &mut info,
            )
        } == 0
        {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    })?;
    // SAFETY: Successful CreateProcessW transfers both handles to the caller.
    let (process, primary_thread) = unsafe {
        (
            OwnedHandle::from_raw_handle(info.hProcess),
            OwnedHandle::from_raw_handle(info.hThread),
        )
    };
    Ok(Child {
        wait: None,
        process,
        primary_thread: Some(primary_thread),
        pid: info.dwProcessId,
        exit: None,
        kill_on_drop: true,
        stdout: Some(stdout),
        stderr: Some(stderr),
    })
}

/// Accept an `.exe`, or a path with no extension resolved the way std's
/// `Command` resolves it: `<path>.exe` when that file exists, otherwise the
/// path itself. CreateProcessW hands only `.bat` and `.cmd` files to cmd.exe;
/// a file with no extension either loads as an executable image or fails, so
/// neither case reaches batch parsing. Every other extension is refused.
fn resolve_program(program: &Path) -> io::Result<PathBuf> {
    match program.extension() {
        Some(ext) if ext.eq_ignore_ascii_case("exe") => Ok(program.to_path_buf()),
        None => {
            let mut exe = program.as_os_str().to_owned();
            exe.push(".exe");
            let exe = PathBuf::from(exe);
            Ok(if exe.is_file() {
                exe
            } else {
                program.to_path_buf()
            })
        }
        Some(_) => Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "Windows module program must be an .exe or have no extension",
        )),
    }
}

fn command_line<'a>(
    program: &OsStr,
    args: impl IntoIterator<Item = &'a OsStr>,
) -> io::Result<Vec<u16>> {
    const QUOTE: u16 = b'"' as u16;
    const SPACE: u16 = b' ' as u16;
    const TAB: u16 = b'\t' as u16;
    const SLASH: u16 = b'\\' as u16;
    let program = wide_without_nul(program)?;
    if program.contains(&QUOTE) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "executable path contains a quote",
        ));
    }
    // The CRT parses argv[0] as a quoted executable name, not as a regular argument.
    let mut line = Vec::from([QUOTE]);
    line.extend(program);
    line.push(QUOTE);
    for arg in args {
        let arg = wide_without_nul(arg)?;
        line.push(SPACE);
        let quoted = arg.is_empty() || arg.contains(&SPACE) || arg.contains(&TAB);
        if quoted {
            line.push(QUOTE);
        }
        let mut slashes = 0;
        for ch in arg {
            match ch {
                SLASH => slashes += 1,
                _ => {
                    let escapes = if ch == QUOTE {
                        2 * slashes + 1
                    } else {
                        slashes
                    };
                    line.extend(std::iter::repeat_n(SLASH, escapes));
                    line.push(ch);
                    slashes = 0;
                }
            }
        }
        line.extend(std::iter::repeat_n(
            SLASH,
            if quoted { 2 * slashes } else { slashes },
        ));
        if quoted {
            line.push(QUOTE);
        }
    }
    line.push(0);
    Ok(line)
}

fn null_input() -> io::Result<OwnedHandle> {
    let nul = [b'N' as u16, b'U' as u16, b'L' as u16, 0];
    let attributes = SECURITY_ATTRIBUTES {
        nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: null_mut(),
        bInheritHandle: 1,
    };
    // SAFETY: NUL is terminated and the attributes live through the call.
    let handle = unsafe {
        CreateFileW(
            nul.as_ptr(),
            GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            &attributes,
            OPEN_EXISTING,
            0,
            null_mut(),
        )
    };
    if handle == INVALID_HANDLE_VALUE {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: CreateFileW returned a new owned handle.
    Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}

fn output_pipe() -> io::Result<(OwnedHandle, OwnedHandle)> {
    let (mut reader, mut writer) = (null_mut(), null_mut());
    // SAFETY: Both outputs are writable. Neither handle is initially inheritable.
    if unsafe { CreatePipe(&mut reader, &mut writer, null(), 0) } == 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: CreatePipe succeeded and transferred a new pair of handles.
    let (reader, writer) = unsafe {
        (
            OwnedHandle::from_raw_handle(reader),
            OwnedHandle::from_raw_handle(writer),
        )
    };
    let mut child_writer = null_mut();
    // SAFETY: DuplicateHandle borrows the live writer and writes the new handle.
    // Only the child end can be inherited; the daemon's reader never can.
    if unsafe {
        let process = GetCurrentProcess();
        DuplicateHandle(
            process,
            writer.as_raw_handle(),
            process,
            &mut child_writer,
            0,
            1,
            DUPLICATE_SAME_ACCESS,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: DuplicateHandle returned a new owned handle.
    Ok((reader, unsafe {
        OwnedHandle::from_raw_handle(child_writer)
    }))
}

struct Attributes<'a> {
    storage: Vec<usize>,
    _handles: &'a [RawHandle; 3],
}

impl<'a> Attributes<'a> {
    fn new(handles: &'a [RawHandle; 3]) -> io::Result<Self> {
        let mut bytes = 0;
        // SAFETY: A null list is the documented size query.
        unsafe { InitializeProcThreadAttributeList(null_mut(), 1, 0, &mut bytes) };
        if bytes == 0 {
            return Err(io::Error::last_os_error());
        }
        let mut storage = vec![0usize; bytes.div_ceil(size_of::<usize>())];
        // SAFETY: The buffer is pointer-aligned and at least the requested size.
        if unsafe {
            InitializeProcThreadAttributeList(storage.as_mut_ptr().cast(), 1, 0, &mut bytes)
        } == 0
        {
            return Err(io::Error::last_os_error());
        }
        let mut list = Self {
            storage,
            _handles: handles,
        };
        // SAFETY: The list is initialized and the fixed-size handle array stays
        // live through CreateProcessW and until the attribute list is deleted.
        if unsafe {
            UpdateProcThreadAttribute(
                list.as_mut_ptr(),
                0,
                PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,
                handles.as_ptr().cast(),
                size_of_val(handles),
                null_mut(),
                null(),
            )
        } == 0
        {
            return Err(io::Error::last_os_error());
        }
        Ok(list)
    }

    fn as_mut_ptr(&mut self) -> *mut std::ffi::c_void {
        self.storage.as_mut_ptr().cast()
    }
}

impl Drop for Attributes<'_> {
    fn drop(&mut self) {
        // SAFETY: Only a successfully initialized list is wrapped in Attributes.
        unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) };
    }
}

#[cfg(test)]
#[path = "windows_spawn_tests.rs"]
mod tests;