artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Job Objects: a child starts suspended in a new console process group, joins a
//! kill-on-close job, and its primary thread resumes only when the gate admits it.

use std::{
    fs::File,
    io, mem,
    os::windows::io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
    path::PathBuf,
    sync::{Arc, Mutex},
};

use crate::platform::executable::{Console, Lease, open_executable, same_file, windows::ImageView};

use super::ResolvedCommand;
use tokio::{
    process::{ChildStderr, ChildStdin, ChildStdout, Command},
    sync::oneshot,
    task::JoinHandle,
};
use windows_sys::Win32::{
    Foundation::{
        ERROR_ACCESS_DENIED, ERROR_CANCELLED, ERROR_INVALID_PARAMETER, FILETIME,
        GetHandleInformation, HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE,
        SetHandleInformation, WAIT_TIMEOUT,
    },
    System::{
        Console::{
            CTRL_BREAK_EVENT, GenerateConsoleCtrlEvent, GetStdHandle, STD_ERROR_HANDLE,
            STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
        },
        Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
        },
        Threading::{
            CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW,
            CREATE_SUSPENDED, DETACHED_PROCESS, GetProcessTimes, OpenProcess, OpenThread,
            PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, ResumeThread,
            THREAD_SUSPEND_RESUME, WaitForSingleObject,
        },
    },
};

mod job;
use job::Job;

pub(super) struct Binding {
    identity: Option<Identity>,
    image: Lease,
    batch: bool,
}

/// Windows denies write/delete sharing on the verified image and its ancestors. Keep
/// those pins through CreateProcess and the admission of its suspended child.
struct Identity {
    path: PathBuf,
    file: File,
    _guards: Vec<File>,
    _section: Option<ImageView>,
}

impl Binding {
    fn verify(&self) -> io::Result<()> {
        if let Some(identity) = &self.identity
            && !same_file(&identity.file, &identity.path)?
        {
            return Err(io::ErrorKind::PermissionDenied.into());
        }
        Ok(())
    }
}

impl ResolvedCommand {
    pub(in crate::platform) fn ordinary(command: Command, image: Lease, batch: bool) -> Self {
        Self {
            command,
            binding: Binding {
                identity: None,
                image,
                batch,
            },
        }
    }

    pub(in crate::platform) fn verified(
        command: Command,
        image: Lease,
        batch: bool,
        guards: Vec<File>,
        section: Option<ImageView>,
    ) -> io::Result<Self> {
        let path = PathBuf::from(command.as_std().get_program());
        let file = open_executable(&path)?;
        Ok(Self {
            command,
            binding: Binding {
                identity: Some(Identity {
                    path,
                    file,
                    _guards: guards,
                    _section: section,
                }),
                image,
                batch,
            },
        })
    }

    fn check_working_directory(&self) -> io::Result<()> {
        if !self.binding.batch {
            return Ok(());
        }
        // The caller can set current_dir after resolving the program. Validate at
        // the native spawn boundary, including an inherited working directory.
        let cwd = self
            .as_std()
            .get_current_dir()
            .map_or_else(std::env::current_dir, |cwd| Ok(cwd.to_owned()))?;
        use super::super::executable::windows::batch::check_working_directory;
        check_working_directory(&cwd)?;
        check_working_directory(&std::fs::canonicalize(cwd)?)
    }

    /// Start the exact image without altering its process group or Job.
    pub fn spawn(mut self) -> io::Result<tokio::process::Child> {
        self.check_working_directory()?;
        let _guard = SPAWN.lock().unwrap();
        self.binding.verify()?;
        let child = self.command.spawn()?;
        retain_child_image(&child, self.binding.image)?;
        Ok(child)
    }
}

/// Every spawn in this module uses this lock while CreateProcess observes inheritable
/// handles. In particular, it must not overlap detached stdio suppression and restoration.
static SPAWN: Mutex<()> = Mutex::new(());

/// The child and its job; every process in the job is killed when this drops, unless the
/// child was released.
pub struct Child {
    child: tokio::process::Child,
    job: Job,
    terminating: Option<Arc<[OwnedHandle]>>,
    group: super::ProcessId,
    _leader: OwnedHandle,
    released: bool,
    _verified: Option<Lease>,
    _image: Lease,
}

use super::ProcessOutcome;

impl Child {
    pub fn stdin(&mut self) -> &mut Option<ChildStdin> {
        &mut self.child.stdin
    }

    pub fn stdout(&mut self) -> &mut Option<ChildStdout> {
        &mut self.child.stdout
    }

    pub fn stderr(&mut self) -> &mut Option<ChildStderr> {
        &mut self.child.stderr
    }

    pub async fn wait(&mut self) -> io::Result<ProcessOutcome> {
        self.child.wait().await.map(ProcessOutcome::from_native)
    }

    pub async fn wait_leader(&mut self) -> io::Result<ProcessOutcome> {
        self.child.wait().await.map(ProcessOutcome::from_native)
    }

    pub fn try_wait_leader(&mut self) -> io::Result<Option<ProcessOutcome>> {
        self.child
            .try_wait()
            .map(|status| status.map(ProcessOutcome::from_native))
    }

    /// Ask the child's console process group to stop with Ctrl-Break, the closest to SIGTERM.
    /// This fails when the child shares no console with artifactize; the job is killed after
    /// the grace period either way.
    pub fn interrupt(&self) -> io::Result<()> {
        // Keep the original group after waiting for the leader; a surviving
        // console member can still receive Ctrl-Break. Do not signal an empty Job.
        if self.job.active_processes()? == 0 {
            return Ok(());
        }
        // SAFETY: a nonzero group id reaches only that console process group.
        if unsafe { GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, self.group.get()) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }

    /// Stop the leader and every descendant in the Job (breakaway is disallowed),
    /// and wait for termination.
    pub async fn cleanup(&mut self) -> io::Result<ProcessOutcome> {
        self.kill()?;
        let status = self.child.wait().await?;
        let processes = self
            .terminating
            .clone()
            .expect("kill retained process handles");
        if !processes.is_empty() {
            tokio::task::spawn_blocking(move || job::wait_for_exit(&processes))
                .await
                .map_err(join_error)??;
        }
        Ok(ProcessOutcome::from_native(status))
    }

    /// Terminate every process in the job.
    pub fn kill(&mut self) -> io::Result<()> {
        if self.terminating.is_none() {
            let processes = self.job.processes_for_cleanup();
            // Even if obtaining waitable handles failed, still kill the whole Job.
            self.job.terminate()?;
            self.terminating = Some(processes?.into());
        }
        Ok(())
    }

    /// Let what the child left running, such as a browser it opened, go on: the job no longer
    /// kills its processes when it closes, and dropping this kills nothing.
    pub fn release(mut self) -> io::Result<()> {
        let process = (self._image.has_resources()
            || self._verified.as_ref().is_some_and(Lease::has_resources))
        .then(|| self._leader.try_clone())
        .transpose()?;
        self.job.keep_on_close()?;
        self.released = true;
        if let Some(process) = process {
            retain_images_until_exit(
                process,
                (self._verified.take(), mem::take(&mut self._image)),
            );
        }
        Ok(())
    }
}

impl Drop for Child {
    fn drop(&mut self) {
        if !self.released {
            let _ = self.job.terminate();
        }
    }
}

/// Holds a suspended child until admitted. Dropping it unadmitted kills the child before it
/// runs any code.
pub struct Gate {
    pid: u32,
    admission: oneshot::Sender<()>,
    binding: Binding,
}

/// The suspended child after its PID has been made available to the caller.
pub struct IdentifiedGate(Gate);

impl Gate {
    pub async fn identify(self) -> io::Result<IdentifiedGate> {
        Ok(IdentifiedGate(self))
    }
}

impl IdentifiedGate {
    pub fn pid(&self) -> u32 {
        self.0.pid
    }

    /// Resume the child's primary thread: only now does it start to run.
    pub fn admit(self) -> io::Result<()> {
        self.0.binding.verify()?;
        resume(self.0.pid)?;
        self.0
            .admission
            .send(())
            .map_err(|_| io::ErrorKind::BrokenPipe.into())
    }
}

/// Spawn a program suspended in an owned Job until the gate admits it.
pub fn spawn_gated(command: ResolvedCommand) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
    spawn_gated_with(command, 0)
}

fn spawn_gated_with(
    mut command: ResolvedCommand,
    flags: u32,
) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
    command.check_working_directory()?;
    let job = Job::new()?;
    command
        .command
        .creation_flags(CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP | flags)
        .kill_on_drop(false);
    // The application passed to std has already been made exact, including batch shims.
    let spawned = {
        let _guard = SPAWN.lock().unwrap();
        command.binding.verify()?;
        command.command.spawn()
    };
    let child = spawned.and_then(|mut child| match job.assign(&child) {
        Ok(()) => Ok(child),
        Err(error) => {
            // Still suspended, so nothing ran; kill it whatever its kill_on_drop says.
            let _ = child.start_kill();
            Err(error)
        }
    })?;
    let process = child
        .raw_handle()
        .expect("a suspended process has a handle");
    // SAFETY: the live, owned child contains this handle until it is waited or
    // dropped. Duplicate it to reserve the console group ID after leader exit.
    let leader = unsafe { BorrowedHandle::borrow_raw(process) }.try_clone_to_owned()?;
    let (outcome, admission) = oneshot::channel();
    let group = super::ProcessId::new(child.id().expect("a newly spawned child has a PID"));
    let image = command.binding.image.clone();
    let gate = Gate {
        binding: command.binding,
        pid: group.get(),
        admission: outcome,
    };
    let spawning = tokio::spawn(async move {
        let mut child = child;
        if admission.await.is_err() {
            let _ = job.terminate();
            let _ = child.wait().await;
            return Err(io::Error::from_raw_os_error(ERROR_CANCELLED as i32));
        }
        Ok(Child {
            child,
            job,
            terminating: None,
            group,
            _leader: leader,
            released: false,
            _verified: None,
            _image: image,
        })
    });
    Ok((gate, spawning))
}

pub(in crate::platform) fn spawn_for_admission(
    command: ResolvedCommand,
    console: Console,
) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
    let flags = match console {
        Console::Inherit => 0,
        Console::Hidden => CREATE_NO_WINDOW,
    };
    spawn_gated_with(command, flags)
}

impl Child {
    pub(in crate::platform) fn retain_image(&mut self, lease: Lease) {
        self._verified = Some(lease);
    }
}

/// Spawn `command` as [`spawn_gated`] does and admit it at once: it joins its job before it
/// runs.
pub async fn spawn_now(command: ResolvedCommand) -> io::Result<Child> {
    admitted(spawn_gated(command)?).await
}

/// Windows always uses its Job, including for work recovered by an owner.
pub use spawn_now as spawn_in_owner_session;

fn join_error(error: tokio::task::JoinError) -> io::Error {
    if error.is_panic() {
        std::panic::resume_unwind(error.into_panic());
    }
    io::Error::new(io::ErrorKind::Interrupted, error)
}

/// Admit a gated child at once.
async fn admitted((gate, spawning): (Gate, JoinHandle<io::Result<Child>>)) -> io::Result<Child> {
    gate.identify().await?.admit()?;
    spawning.await.map_err(join_error)?
}

/// Spawn a program that hands part of its work to the desktop, such as a sign-in that opens
/// the browser, as [`spawn_now`] does but without a console window. It gets a hidden console
/// of its own rather than none: a console program it starts, such as the `node` behind a
/// `.cmd` shim, then shares that console and the pipes, where without a console
/// (`DETACHED_PROCESS`) Windows would give it a new console and its output would go there.
/// Its job keeps it and everything it starts from outliving its owner.
pub async fn spawn_windowless(command: ResolvedCommand) -> io::Result<Child> {
    admitted(spawn_gated_with(command, CREATE_NO_WINDOW)?).await
}

/// Resume every thread of a process created suspended; it has exactly one. Its handle is
/// held by the spawning task, so the PID cannot be reused meanwhile.
fn resume(pid: u32) -> io::Result<()> {
    // SAFETY: a snapshot of all threads; the result is checked and then owned.
    let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
    if snapshot == INVALID_HANDLE_VALUE {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: CreateToolhelp32Snapshot returned a new handle that nothing else owns.
    let snapshot = unsafe { OwnedHandle::from_raw_handle(snapshot) };
    let mut entry = THREADENTRY32 {
        dwSize: mem::size_of::<THREADENTRY32>() as u32,
        ..Default::default()
    };
    let mut resumed = false;
    // SAFETY: an open snapshot and an entry whose dwSize is set.
    let mut more = unsafe { Thread32First(snapshot.as_raw_handle(), &mut entry) } != 0;
    while more {
        if entry.th32OwnerProcessID == pid {
            // SAFETY: the result is checked and then owned.
            let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
            if thread.is_null() {
                return Err(io::Error::last_os_error());
            }
            // SAFETY: OpenThread returned a new handle that nothing else owns.
            let thread = unsafe { OwnedHandle::from_raw_handle(thread) };
            // SAFETY: an open thread handle with THREAD_SUSPEND_RESUME.
            if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
                return Err(io::Error::last_os_error());
            }
            resumed = true;
        }
        // SAFETY: as for Thread32First.
        more = unsafe { Thread32Next(snapshot.as_raw_handle(), &mut entry) } != 0;
    }
    if !resumed {
        return Err(io::Error::other(
            "the suspended child has no thread to resume",
        ));
    }
    Ok(())
}

/// Spawn outside artifactize's console, process group and job, for a desktop handoff that
/// outlives it: a terminal, IDE or CI runner may hold artifactize in a kill-on-close job. A
/// job that forbids breakaway refuses that spawn with access denied; the handoff then starts
/// inside the job, as it did before.
pub fn spawn_detached(mut command: ResolvedCommand) -> io::Result<tokio::process::Child> {
    command.check_working_directory()?;
    let _guard = SPAWN.lock().unwrap();
    let _suppressed = SuppressedStdio::new();
    let detached = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
    command
        .command
        .creation_flags(detached | CREATE_BREAKAWAY_FROM_JOB);
    command.binding.verify()?;
    let child = match command.command.spawn() {
        Err(error) if error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => {
            command.command.creation_flags(detached);
            command.binding.verify()?;
            command.command.spawn()
        }
        spawned => spawned,
    }?;
    // A handoff is not killed or waited on by its requester. Keep a private executable or
    // batch lease alive until the detached process exits, even if its caller drops Child.
    retain_child_image(&child, command.binding.image)?;
    Ok(child)
}

fn retain_child_image(child: &tokio::process::Child, image: Lease) -> io::Result<()> {
    if image.has_resources() {
        let handle = child
            .raw_handle()
            .expect("a just-spawned child has a process handle");
        // SAFETY: Child still owns this handle; clone it for the detached waiter.
        let process = unsafe { BorrowedHandle::borrow_raw(handle) }.try_clone_to_owned()?;
        retain_images_until_exit(process, image);
    }
    Ok(())
}

fn retain_images_until_exit(process: OwnedHandle, images: impl Send + 'static) {
    std::thread::spawn(move || {
        // SAFETY: own the process handle until it is signalled on exit.
        unsafe { WaitForSingleObject(process.as_raw_handle(), u32::MAX) };
        drop(images);
    });
}

/// Detached children must not keep the launcher's pipes alive by inheriting its handles
/// in addition to the child-specific stdio that `Command` supplies. Restore only flags this
/// spawn actually changed, including on failure or the breakaway retry.
struct SuppressedStdio([Option<HANDLE>; 3]);

impl SuppressedStdio {
    fn new() -> Self {
        Self(
            [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE].map(|id| {
                let mut flags = 0;
                // SAFETY: the handle query takes a standard stream identifier; the flag query
                // and update validate their handles, and `flags` is a live out parameter.
                unsafe {
                    let handle = GetStdHandle(id);
                    (GetHandleInformation(handle, &mut flags) != 0
                        && flags & HANDLE_FLAG_INHERIT != 0
                        && SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) != 0)
                        .then_some(handle)
                }
            }),
        )
    }
}

impl Drop for SuppressedStdio {
    fn drop(&mut self) {
        for handle in self.0.into_iter().flatten() {
            // SAFETY: these are process-owned standard handles whose flags we changed under
            // the spawn lock; SetHandleInformation validates the handle again on restore.
            unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) };
        }
    }
}

/// Run workers also detach from their requester when its enclosing Job forbids breakaway;
/// that Job's lifetime remains an OS-imposed bound, just as for a desktop handoff.
pub fn spawn_run(command: ResolvedCommand) -> io::Result<tokio::process::Child> {
    spawn_detached(command)
}

/// A desktop handoff whose output pipes a Tool log drains. A write to a pipe nobody reads
/// fails with an error on Windows; no signal ends the program.
pub fn spawn_watched(command: ResolvedCommand) -> io::Result<tokio::process::Child> {
    spawn_detached(command)
}

/// A host probe such as Git runs without a console window. A console program started by a
/// process that has no console, such as the desktop app, would otherwise get a window of its
/// own until it exits. The probe's output goes through pipes, so the window shows nothing.
pub fn hide_console_window(command: &mut std::process::Command) {
    use std::os::windows::process::CommandExt;
    command.creation_flags(CREATE_NO_WINDOW);
}

/// The creation time, in 100 ns intervals since 1601. A process that has exited counts as
/// not found, as does one this user may not query: artifactize records only its own
/// processes and children, so such a PID was reused by another user's or a system process.
pub fn process_start_time(pid: u32) -> io::Result<u64> {
    // SAFETY: the result is checked and then owned.
    let process = unsafe {
        OpenProcess(
            PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE,
            0,
            pid,
        )
    };
    if process.is_null() {
        let error = io::Error::last_os_error();
        return Err(match error.raw_os_error().map(|code| code as u32) {
            Some(ERROR_INVALID_PARAMETER | ERROR_ACCESS_DENIED) => io::ErrorKind::NotFound.into(),
            _ => error,
        });
    }
    // SAFETY: OpenProcess returned a new handle that nothing else owns.
    let process = unsafe { OwnedHandle::from_raw_handle(process) };
    // A process handle is signaled on exit, including a real exit code of 259.
    // SAFETY: the owned process handle permits synchronization; zero never blocks.
    match unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } {
        WAIT_TIMEOUT => {}
        windows_sys::Win32::Foundation::WAIT_FAILED => return Err(io::Error::last_os_error()),
        _ => return Err(io::ErrorKind::NotFound.into()),
    }
    let mut creation = FILETIME::default();
    let (mut exit, mut kernel, mut user) = (creation, creation, creation);
    // SAFETY: an open process handle and valid out pointers.
    if unsafe {
        GetProcessTimes(
            process.as_raw_handle(),
            &mut creation,
            &mut exit,
            &mut kernel,
            &mut user,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime))
}

/// Windows identity lookup already excludes a signalled (terminated) process.
pub fn running_process_start_time(pid: u32) -> io::Result<u64> {
    process_start_time(pid)
}

/// Every owned preparation/execution child has a kill-on-close Job held by its Run worker.
pub fn kill_saved_session(_leader: super::ChildIdentity) -> io::Result<()> {
    Ok(())
}

/// A dead owner has already closed its kill-on-close Job handle.
pub fn kill_saved_group(_leader: super::ChildIdentity) -> io::Result<()> {
    Ok(())
}