artifactize-foundation 0.27.1

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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
//! Process sessions, the pre-exec admission gate, and OS process start times.

use std::{
    io::{self, Read, Write},
    net::Shutdown,
    os::{fd::AsRawFd, unix::net::UnixStream},
    sync::{Arc, mpsc},
};

use crate::platform::executable::{Console, Lease};
use rustix::{
    io::Errno,
    process::{Pid, Signal, WaitId, WaitIdOptions},
};
use tokio::{
    io::unix::AsyncFd,
    process::{ChildStderr, ChildStdin, ChildStdout, Command},
    signal::unix::{SignalKind, signal},
    task::JoinHandle,
};

use super::{Program, ResolvedCommand};

pub(super) type Binding = Option<Box<dyn Fn() -> io::Result<()> + Send + Sync>>;

impl Program {
    /// Execute the resolved path. The kernel handles its native loader or shebang.
    pub fn command(
        self,
        args: impl IntoIterator<Item = impl AsRef<std::ffi::OsStr>>,
    ) -> io::Result<ResolvedCommand> {
        let mut command = Command::new(self.canonical);
        // Multicall binaries (including toolchain shims) select a mode from argv[0].
        command.arg0(self.path).args(args);
        Ok(ResolvedCommand {
            command,
            binding: None,
        })
    }
}

impl ResolvedCommand {
    pub(in crate::platform) fn verified(
        command: Command,
        verify: impl Fn() -> io::Result<()> + Send + Sync + 'static,
    ) -> Self {
        Self {
            command,
            binding: Some(Box::new(verify)),
        }
    }

    /// Start the exact image without altering its process group.
    pub fn spawn(mut self) -> io::Result<tokio::process::Child> {
        if let Some(verify) = self.binding {
            // SAFETY: each binding uses only async-signal-safe operations and memory
            // prepared before fork. It runs last, immediately before native exec.
            unsafe { self.command.pre_exec(verify) };
        }
        self.command.spawn()
    }
}

/// The child's process scope, killed when dropped.
pub struct Child {
    child: Option<tokio::process::Child>,
    group: Group,
    scope: Scope,
    verified: Option<Lease>,
}

enum Group {
    Owned(super::ChildIdentity),
    Signalled(super::ChildIdentity),
    Released,
}

#[derive(Clone)]
enum Scope {
    Session,
    Owner(Arc<Owner>),
}

struct Owner {
    tree: tree::Descendants,
    #[cfg(target_os = "linux")]
    reaper: reaper::Reaper,
}

use super::ProcessOutcome;

impl Child {
    fn child(&mut self) -> &mut tokio::process::Child {
        self.child
            .as_mut()
            .expect("native child only taken in Drop")
    }

    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
    }

    /// Observe the workload leader's exit without surrendering its scope. The
    /// native child reserves the session ID or anchors the descendant tree.
    pub async fn wait(&mut self) -> io::Result<ProcessOutcome> {
        self.wait_leader().await
    }

    pub async fn wait_leader(&mut self) -> io::Result<ProcessOutcome> {
        // Repeated checks register for SIGCHLD first, so a fast exit cannot lose its wakeup.
        drop(self.child().stdin.take());
        #[cfg(target_os = "linux")]
        if let Scope::Owner(owner) = &self.scope {
            return owner.reaper.wait().await;
        }
        let mut exited = signal(SignalKind::child())?;
        loop {
            if let Some(status) = self.try_wait_leader()? {
                return Ok(status);
            }
            exited.recv().await.ok_or(io::ErrorKind::BrokenPipe)?;
        }
    }

    pub fn try_wait_leader(&mut self) -> io::Result<Option<ProcessOutcome>> {
        use std::{os::unix::process::ExitStatusExt, process::ExitStatus};

        #[cfg(target_os = "linux")]
        if let Scope::Owner(owner) = &self.scope {
            return owner.reaper.try_wait();
        }
        let Some(pid) = self.child().id() else {
            return self
                .child()
                .try_wait()
                .map(|status| status.map(ProcessOutcome::from_native));
        };
        let pid = native_pid(pid)?;
        let status = loop {
            match rustix::process::waitid(
                WaitId::Pid(pid),
                WaitIdOptions::EXITED | WaitIdOptions::NOWAIT | WaitIdOptions::NOHANG,
            ) {
                Err(Errno::INTR) => continue,
                result => break result?,
            }
        };
        Ok(status.map(|status| {
            // waitid reports the exit code or signal separately, not a waitpid word.
            // POSIX Unix waitpid stores normal exit in the high byte and core in bit 7.
            const EXIT_CODE_SHIFT: u32 = 8;
            const CORE_DUMPED: i32 = 0x80;
            let raw = if let Some(code) = status.exit_status() {
                code << EXIT_CODE_SHIFT
            } else {
                status
                    .terminating_signal()
                    .expect("WEXITED only reports a terminal status")
                    | if status.dumped() { CORE_DUMPED } else { 0 }
            };
            ProcessOutcome::from_native(ExitStatus::from_raw(raw))
        }))
    }

    /// Ask the process and its children to stop with SIGTERM.
    pub fn interrupt(&self) -> io::Result<()> {
        if let Group::Owned(group) = self.group {
            signal_scope(group, &self.scope, Signal::TERM)
        } else {
            Ok(())
        }
    }

    /// Stop the process and its children; an already exited member is not an error.
    pub fn kill(&mut self) -> io::Result<()> {
        if let Group::Owned(group) = self.group {
            signal_scope(group, &self.scope, Signal::KILL)?;
            // No later wait, cleanup or Drop may signal this numeric PGID again.
            self.group = Group::Signalled(group);
        }
        Ok(())
    }

    /// Stop the leader and wait for its owned scope to drain. An owned Unix
    /// session includes subordinate groups, even after the leader exits. For work
    /// in the owner's session, see [`spawn_in_owner_session`] for OS guarantees.
    pub async fn cleanup(&mut self) -> io::Result<ProcessOutcome> {
        self.kill()?;
        if let Group::Signalled(group) = self.group {
            let scope = self.scope.clone();
            tokio::task::spawn_blocking(move || finish_scope(group, scope))
                .await
                .map_err(io::Error::other)??;
            self.group = Group::Released;
        }
        let outcome = self.wait_leader().await?;
        let native = self.child().wait().await?;
        if cfg!(target_os = "linux") && matches!(self.scope, Scope::Owner(_)) && !native.success() {
            return Err(io::Error::other(
                "the process reaper exited before draining its children",
            ));
        }
        Ok(outcome)
    }

    /// Let the workload and its descendants go on, for example a browser it opened.
    pub fn release(mut self) -> io::Result<()> {
        #[cfg(target_os = "linux")]
        if matches!(self.scope, Scope::Owner(_))
            && let Group::Owned(reaper) = self.group
        {
            // This PID belongs to the reaper, not to the program being released.
            vanished(
                rustix::process::kill_process(native_pid(reaper.pid.get())?, Signal::KILL)
                    .map_err(io::Error::from),
            )?;
        }
        self.group = Group::Released;
        #[cfg(target_os = "macos")]
        if self.verified.as_ref().is_some_and(Lease::has_resources) {
            // On macOS the interpreter may not have opened its staged script yet.
            // Keep the path alive even if the caller shuts down its async runtime.
            let mut child = self.child.take().expect("release owns the native child");
            let lease = self.verified.take();
            std::thread::spawn(move || {
                let _lease = lease;
                if let Some(pid) = child.id().and_then(|pid| native_pid(pid).ok()) {
                    while let Err(Errno::INTR) = rustix::process::waitid(
                        WaitId::Pid(pid),
                        WaitIdOptions::EXITED | WaitIdOptions::NOWAIT,
                    ) {}
                }
                let _ = child.try_wait();
            });
        }
        Ok(())
    }
}

fn native_pid(pid: u32) -> io::Result<Pid> {
    i32::try_from(pid)
        .ok()
        .and_then(Pid::from_raw)
        .ok_or(io::ErrorKind::InvalidInput.into())
}

fn native_group(pid: Pid) -> io::Result<Option<Pid>> {
    // Some WSL system processes return a successful zero (outside a process group).
    // rustix's getpgid assumes success is strictly positive and panics on that result.
    // SAFETY: the query takes a valid positive PID and no pointers.
    let raw = unsafe { libc::getpgid(pid.as_raw_pid()) };
    if raw < 0 {
        return vanished::<Pid>(Err(io::Error::last_os_error()));
    }
    Ok(Pid::from_raw(raw))
}

fn native_session(pid: Pid) -> io::Result<Option<Pid>> {
    // WSL may similarly report that a kernel-managed process has no session.
    // SAFETY: the query takes a valid positive PID and no pointers.
    let raw = unsafe { libc::getsid(pid.as_raw_pid()) };
    if raw < 0 {
        return vanished::<Pid>(Err(io::Error::last_os_error()));
    }
    Ok(Pid::from_raw(raw))
}

fn vanished<T>(result: io::Result<T>) -> io::Result<Option<T>> {
    match result {
        Ok(value) => Ok(Some(value)),
        Err(error)
            if error.kind() == io::ErrorKind::NotFound
                || error.raw_os_error() == Some(libc::ESRCH) =>
        {
            Ok(None)
        }
        Err(error) => Err(error),
    }
}

fn wait_empty(group: super::ChildIdentity, scope: &Scope) -> io::Result<()> {
    use std::time::{Duration, Instant};
    // Like Windows Job cleanup, wait for forced termination to take effect. Bound
    // a descendant stuck inside the kernel.
    const CLEANUP_TIMEOUT: Duration = Duration::from_secs(30);
    const CHECK_INTERVAL: Duration = Duration::from_millis(10);
    let deadline = Instant::now() + CLEANUP_TIMEOUT;
    loop {
        // A descendant can fork while earlier members are receiving signals.
        // Rescan without sending another signal to a numeric process group.
        let live = match scope {
            Scope::Session => signal_members(group, native_session, Signal::KILL)?,
            Scope::Owner(owner) => {
                let found = owner.tree.signal(group, Signal::KILL)?;
                #[cfg(target_os = "linux")]
                // The dedicated reaper only exits after waitpid reports no children.
                // In particular, nobody was missed while being reparented between scans.
                let found = found || super::is_alive(Some(group))?;
                found
            }
        };
        if !live {
            return Ok(());
        }
        if Instant::now() >= deadline {
            return Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "process descendants did not terminate",
            ));
        }
        std::thread::sleep(CHECK_INTERVAL);
    }
}

/// Darwin proc_info.h: a process committed to exit() can still report SRUN
/// before becoming SZOMB. It can no longer execute user code or fork descendants.
#[cfg(target_os = "macos")]
const PROC_FLAG_INEXIT: u32 = 4;

#[cfg(target_os = "macos")]
fn process_group_exited(pgid: u32) -> io::Result<bool> {
    let pgid = i32::try_from(pgid).map_err(|_| io::ErrorKind::InvalidInput)?;
    // libproc returns PID counts, not bytes, including spare capacity on a size query.
    // SAFETY: a null buffer asks for capacity and does not read or write records.
    let (capacity, error) = unsafe {
        *libc::__error() = 0;
        let read = libc::proc_listpgrppids(pgid, std::ptr::null_mut(), 0);
        (read, io::Error::last_os_error())
    };
    if capacity == 0 && matches!(error.raw_os_error(), Some(0 | libc::ESRCH)) {
        return Ok(true);
    }
    if capacity <= 0 {
        return Err(error);
    }
    let bytes = capacity
        .checked_mul(std::mem::size_of::<i32>() as i32)
        .ok_or_else(|| io::Error::other("process group information size overflow"))?;
    // Bound kernel-reported allocations and reject a truncated list rather than
    // overlooking a live descendant. No signalling or enumeration retries.
    const MAX_GROUP_INFO_BYTES: i32 = 16 * 1024 * 1024;
    if bytes > MAX_GROUP_INFO_BYTES {
        return Err(io::Error::other("process group information exceeds 16 MiB"));
    }
    let mut pids = vec![0_i32; capacity as usize];
    // libproc also returns zero on error. Clear this thread's errno before the call
    // so an empty group is distinguishable from a failed enumeration.
    // SAFETY: __error returns this thread's writable errno; the aligned PID buffer
    // has the queried byte capacity. Both calls execute on the same thread.
    let (read, error) = unsafe {
        *libc::__error() = 0;
        let read = libc::proc_listpgrppids(pgid, pids.as_mut_ptr().cast(), bytes);
        (read, io::Error::last_os_error())
    };
    if read < 0 || (read == 0 && !matches!(error.raw_os_error(), Some(0 | libc::ESRCH))) {
        return Err(error);
    }
    if read >= capacity {
        return Err(io::Error::other("incomplete process group information"));
    }
    for pid in pids.into_iter().take(read as usize) {
        // Include zombies explicitly. ESRCH means the listed member was reaped
        // during inspection; every other lookup error must remain an error.
        match process_info(pid) {
            Ok(info)
                if info.pbi_pgid == pgid as u32
                    && info.pbi_status != libc::SZOMB
                    && info.pbi_flags & PROC_FLAG_INEXIT == 0 =>
            {
                return Ok(false);
            }
            Ok(_) => {}
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
    }
    Ok(true)
}

fn finish_scope(group: super::ChildIdentity, scope: Scope) -> io::Result<()> {
    wait_empty(group, &scope)?;
    #[cfg(target_os = "linux")]
    if matches!(scope, Scope::Session) {
        subreaper::reap_adopted(group.pid, native_session)?;
    }
    Ok(())
}

impl Drop for Child {
    fn drop(&mut self) {
        let _ = self.kill();
        if let Group::Signalled(group) = self.group
            && let Ok(runtime) = tokio::runtime::Handle::try_current()
        {
            // Keep the leader's numeric ID and its image lease until cleanup drains
            // the owned scope, including if a cleanup future was cancelled.
            let mut child = self.child.take().expect("drop owns the native child");
            let lease = self.verified.take();
            let scope = self.scope.clone();
            runtime.spawn_blocking(move || {
                let _lease = lease;
                let _ = finish_scope(group, scope);
                let _ = child.try_wait();
            });
        }
    }
}

/// Spawn a program in a new session and hold it until the gate admits it.
pub fn spawn_gated(
    mut command: ResolvedCommand,
) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
    configure_session(&mut command.command)?;
    spawn(command)
}

pub(in crate::platform) fn spawn_for_admission(
    command: ResolvedCommand,
    _console: Console,
) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
    spawn_gated(command)
}

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

/// Spawn a supervised command in its own session, running at once.
pub async fn spawn_now(mut command: ResolvedCommand) -> io::Result<Child> {
    configure_session(&mut command.command)?;
    own(command.spawn()?, Scope::Session).await
}

/// Keep the workload in its owner's session for crash recovery, but signal only
/// the launched tree during normal supervision. On Linux a dedicated subreaper
/// retains and reaps orphans, including after a group/session change or leader
/// exit. On macOS ancestry and previously observed process identities are used:
/// an orphan reparented before it can be observed is no longer identifiable.
pub async fn spawn_in_owner_session(command: ResolvedCommand) -> io::Result<Child> {
    #[cfg(target_os = "linux")]
    let (child, reaper) = reaper::Reaper::spawn(command)?;
    #[cfg(target_os = "macos")]
    let child = {
        let mut command = command;
        command.command.process_group(0).kill_on_drop(false);
        command.spawn()?
    };
    own(
        child,
        Scope::Owner(Arc::new(Owner {
            tree: tree::Descendants::default(),
            #[cfg(target_os = "linux")]
            reaper,
        })),
    )
    .await
}

async fn own(mut child: tokio::process::Child, scope: Scope) -> io::Result<Child> {
    let pid = child.id().expect("a newly spawned child has a PID");
    match super::child_identity(pid) {
        Ok(identity) => Ok(Child {
            group: Group::Owned(identity),
            scope,
            child: Some(child),
            verified: None,
        }),
        Err(error) => {
            match scope {
                Scope::Session => {
                    let _ = signal_leader_and_group(super::ProcessId::new(pid), Signal::KILL);
                }
                Scope::Owner(_) => {
                    let _ = child.start_kill();
                }
            }
            let _ = child.wait().await;
            Err(error)
        }
    }
}

fn configure_session(command: &mut Command) -> io::Result<()> {
    #[cfg(target_os = "linux")]
    subreaper::enable()?;
    command.kill_on_drop(false);
    start_session(command);
    Ok(())
}

fn start_session(command: &mut Command) {
    // SAFETY: the forked child calls only setsid, which is async-signal-safe.
    unsafe {
        command.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(io::Error::last_os_error());
            }
            Ok(())
        });
    }
}

/// Spawn in a session of its own, for a desktop handoff that outlives artifactize.
pub fn spawn_detached(mut command: ResolvedCommand) -> io::Result<tokio::process::Child> {
    start_session(&mut command.command);
    command.spawn()
}

pub fn spawn_run(command: ResolvedCommand) -> io::Result<tokio::process::Child> {
    spawn_detached(command)
}

/// 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: Unix programs open no console window.
pub async fn spawn_windowless(command: ResolvedCommand) -> io::Result<Child> {
    spawn_now(command).await
}

/// A desktop handoff whose output pipes a Tool log drains. Like [`spawn_detached`] it gets
/// its own session; it also ignores SIGPIPE, so that once nobody reads the pipes any more (the
/// review's process exited) a write fails with EPIPE instead of killing the program.
pub fn spawn_watched(mut command: ResolvedCommand) -> io::Result<tokio::process::Child> {
    // SAFETY: the forked child calls only setsid and signal, which are async-signal-safe.
    unsafe {
        command.command.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(io::Error::last_os_error());
            }
            if libc::signal(libc::SIGPIPE, libc::SIG_IGN) == libc::SIG_ERR {
                return Err(io::Error::last_os_error());
            }
            Ok(())
        });
    }
    command.spawn()
}

/// Unix programs open no console window; a host probe runs as it is.
pub fn hide_console_window(_command: &mut std::process::Command) {}

/// The index of `starttime` (field 22 of /proc/PID/stat, see proc(5)) among the fields after
/// the command name. The name, field 2, is cut off at its closing parenthesis because it may
/// contain spaces, so the remaining fields start at field 3: 22 - 3 = 19.
#[cfg(not(target_os = "macos"))]
const START_TIME_AFTER_NAME: usize = 22 - 3;

#[cfg(not(target_os = "macos"))]
struct ProcessStat {
    state: ProcessState,
    parent: Option<Pid>,
    start: u64,
}

/// Field 22 of /proc/PID/stat: the start time in clock ticks since boot.
#[cfg(not(target_os = "macos"))]
pub fn process_start_time(pid: u32) -> io::Result<u64> {
    process_stat(pid).map(|stat| stat.start)
}

#[cfg(not(target_os = "macos"))]
fn process_stat(pid: u32) -> io::Result<ProcessStat> {
    // A process that exits between opening its stat file and reading it answers ESRCH:
    // it is gone, as when the file no longer exists.
    let stat = std::fs::read(format!("/proc/{pid}/stat")).map_err(|error| {
        if error.raw_os_error() == Some(libc::ESRCH) {
            io::Error::new(io::ErrorKind::NotFound, error)
        } else {
            error
        }
    })?;
    parse_process_stat(&stat)
}

#[cfg(not(target_os = "macos"))]
enum ProcessState {
    Live,
    Exited,
}

#[cfg(not(target_os = "macos"))]
fn parse_process_stat(stat: &[u8]) -> io::Result<ProcessStat> {
    // comm is arbitrary bytes, possibly containing parentheses. Only the fields after
    // its final ')' have an ASCII grammar; never decode the name as UTF-8.
    let end = stat
        .iter()
        .rposition(|&byte| byte == b')')
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid process stat"))?;
    let mut fields = stat[end + 1..]
        .split(|byte| byte.is_ascii_whitespace())
        .filter(|field| !field.is_empty());
    let state = match fields.next() {
        Some(b"Z" | b"X" | b"x") => ProcessState::Exited,
        Some(b"R" | b"S" | b"D" | b"T" | b"t" | b"W" | b"K" | b"P" | b"I") => ProcessState::Live,
        _ => {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "invalid process state",
            ));
        }
    };
    let parent = fields
        .next()
        .and_then(|field| std::str::from_utf8(field).ok()?.parse().ok())
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid parent process ID"))?;
    let start = fields
        .nth(START_TIME_AFTER_NAME - 2)
        .and_then(|field| std::str::from_utf8(field).ok()?.parse().ok())
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "invalid child process start time",
            )
        })?;
    Ok(ProcessStat {
        state,
        parent: Pid::from_raw(parent),
        start,
    })
}

/// An unreaped zombie still has an identity, but cannot own live execution.
#[cfg(not(target_os = "macos"))]
pub fn running_process_start_time(pid: u32) -> io::Result<u64> {
    let stat = process_stat(pid)?;
    if matches!(stat.state, ProcessState::Exited) {
        Err(io::ErrorKind::NotFound.into())
    } else {
        Ok(stat.start)
    }
}

#[cfg(target_os = "macos")]
pub fn running_process_start_time(pid: u32) -> io::Result<u64> {
    let pid = i32::try_from(pid).map_err(|_| io::ErrorKind::InvalidInput)?;
    let info = process_info(pid)?;
    if info.pbi_status == libc::SZOMB || info.pbi_flags & PROC_FLAG_INEXIT != 0 {
        Err(io::ErrorKind::NotFound.into())
    } else {
        process_birth_time(info)
    }
}

/// macOS exposes the kernel's process birth timestamp, in microseconds since the epoch.
/// Keep its full precision: seconds alone cannot distinguish rapidly reused PIDs.
#[cfg(target_os = "macos")]
pub fn process_start_time(pid: u32) -> io::Result<u64> {
    let pid = i32::try_from(pid).map_err(|_| io::ErrorKind::InvalidInput)?;
    if pid <= 0 {
        return Err(io::ErrorKind::InvalidInput.into());
    }
    process_birth_time(process_info(pid)?)
}

#[cfg(target_os = "macos")]
fn process_birth_time(info: libc::proc_bsdinfo) -> io::Result<u64> {
    const MICROSECONDS_PER_SECOND: u64 = 1_000_000;
    info.pbi_start_tvsec
        .checked_mul(MICROSECONDS_PER_SECOND)
        .and_then(|seconds| seconds.checked_add(info.pbi_start_tvusec))
        .ok_or_else(|| io::Error::other("invalid child process start time"))
}

#[cfg(target_os = "macos")]
fn process_info(pid: i32) -> io::Result<libc::proc_bsdinfo> {
    // Retrieve an unreaped process's identity too; liveness callers distinguish a
    // zombie from an active member by inspecting its status and flags.
    const INCLUDE_ZOMBIES: u64 = 1;
    let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::uninit();
    let size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
    // SAFETY: a writable buffer of the exact size required by PROC_PIDTBSDINFO. The
    // initialized fields are read only if the kernel reports the complete struct.
    let read = unsafe {
        libc::proc_pidinfo(
            pid,
            libc::PROC_PIDTBSDINFO,
            INCLUDE_ZOMBIES,
            info.as_mut_ptr().cast(),
            size,
        )
    };
    if read <= 0 {
        let error = io::Error::last_os_error();
        // proc_pidinfo reports ESRCH for a departed PID; liveness treats this like
        // Linux procfs ENOENT, not a supervision error.
        return Err(if error.raw_os_error() == Some(libc::ESRCH) {
            io::ErrorKind::NotFound.into()
        } else {
            error
        });
    }
    if read != size {
        return Err(io::Error::other("incomplete child process information"));
    }
    // SAFETY: proc_pidinfo wrote the entire struct.
    let info = unsafe { info.assume_init() };
    if info.pbi_pid != pid as u32 {
        return Err(io::Error::other("invalid child process identity"));
    }
    Ok(info)
}

/// The one byte the parent writes on the gate socket to admit the held child past
/// `pre_exec`. Its value carries no meaning beyond "admitted"; the handshake only checks
/// that this exact byte, not some other write, arrived.
const GATE_ADMIT: u8 = 1;

pub struct Gate {
    socket: Arc<AsyncFd<UnixStream>>,
    admitted: mpsc::Sender<super::ChildIdentity>,
}

/// The held child after reading its one-time PID message and capturing its identity.
pub struct IdentifiedGate {
    gate: Gate,
    identity: super::ChildIdentity,
}

impl Gate {
    pub async fn identify(self) -> io::Result<IdentifiedGate> {
        // The child writes its PID as a native-endian u32.
        let mut bytes = [0; size_of::<u32>()];
        let mut offset = 0;
        while offset < bytes.len() {
            let mut ready = self.socket.readable().await?;
            match ready.try_io(|socket| socket.get_ref().read(&mut bytes[offset..])) {
                Ok(Ok(0)) => return Err(io::ErrorKind::UnexpectedEof.into()),
                Ok(Ok(count)) => offset += count,
                Ok(Err(error)) => return Err(error),
                Err(_) => continue,
            }
        }
        let pid = u32::from_ne_bytes(bytes);
        let identity = super::child_identity(pid)?;
        Ok(IdentifiedGate {
            gate: self,
            identity,
        })
    }
}

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

    pub fn admit(self) -> io::Result<()> {
        self.gate.socket.get_ref().write_all(&[GATE_ADMIT])?;
        // A native spawn is not proof of admission: a pre_exec child killed by
        // SIGPIPE also closes std's exec-error pipe without reporting an errno.
        // Publish the saved, inert identity only after opening the gate; the
        // spawning thread waits for this handoff or for Gate drop to cancel it.
        self.gate
            .admitted
            .send(self.identity)
            .map_err(|_| io::ErrorKind::BrokenPipe.into())
    }
}

impl Drop for Gate {
    fn drop(&mut self) {
        // shutdown also disconnects the copy held alive by the spawning thread.
        let _ = self.socket.get_ref().shutdown(Shutdown::Both);
    }
}

fn spawn(command: ResolvedCommand) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
    let ResolvedCommand {
        mut command,
        binding,
    } = command;
    let (parent, child) = UnixStream::pair()?;
    parent.set_nonblocking(true)?;
    let (admitted, admission) = mpsc::channel();
    let gate = Gate {
        socket: Arc::new(AsyncFd::new(parent)?),
        admitted,
    };
    let parent = gate.socket.clone();
    let mut inherited = descriptors::Inherited::reserve();
    // SAFETY: the forked child uses only async-signal-safe syscalls, stack data and the
    // memory reserved above. Both descriptors stay alive until spawn completes; CLOEXEC
    // closes the child endpoint on exec. Closing the inherited parent endpoint makes EOF
    // meaningful. The other runs' pipes this child inherited go before it is held, so
    // that it cannot keep their output open while it waits for admission.
    unsafe {
        command.pre_exec(move || {
            libc::close(parent.get_ref().as_raw_fd());
            let fd = child.as_raw_fd();
            inherited.release(fd);
            let pid = (libc::getpid() as u32).to_ne_bytes();
            let mut offset = 0;
            while offset < pid.len() {
                let written = libc::write(fd, pid[offset..].as_ptr().cast(), pid.len() - offset);
                if written < 0 {
                    let error = io::Error::last_os_error();
                    if error.raw_os_error() == Some(libc::EINTR) {
                        continue;
                    }
                    return Err(error);
                }
                if written == 0 {
                    return Err(io::Error::from_raw_os_error(libc::EPIPE));
                }
                offset += written as usize;
            }
            let mut admission = 0_u8;
            loop {
                match libc::read(fd, (&mut admission as *mut u8).cast(), 1) {
                    1 if admission == GATE_ADMIT => {
                        return binding.as_ref().map_or(Ok(()), |verify| verify());
                    }
                    -1 => {
                        let error = io::Error::last_os_error();
                        if error.raw_os_error() != Some(libc::EINTR) {
                            return Err(error);
                        }
                    }
                    _ => return Err(io::Error::from_raw_os_error(libc::ECANCELED)),
                }
            }
        });
    }
    // std spawn waits for exec's error pipe, so it cannot run on the task that
    // opens the gate. Returning a guarded child also covers a dropped join handle.
    let spawning = tokio::task::spawn_blocking(move || {
        let spawned = command.spawn();
        // Close the parent's captured child endpoint before awaiting admission.
        // If pre_exec died without reporting an errno, Gate::pid must see EOF
        // rather than wait on this copy of the socket for its own cancellation.
        drop(command);
        let mut child = spawned?;
        match admission.recv() {
            Ok(group) => Ok(Child {
                child: Some(child),
                group: Group::Owned(group),
                scope: Scope::Session,
                verified: None,
            }),
            Err(_) => {
                // With no admission byte, a successful native spawn means the
                // pre_exec child died and closed the exec-error pipe. It never
                // executed user code or forked descendants. Reap its owned handle,
                // without inventing an identity or signalling a numeric PGID.
                tokio::runtime::Handle::current().block_on(child.wait())?;
                Err(io::Error::from_raw_os_error(libc::ECANCELED))
            }
        }
    });
    Ok((gate, spawning))
}

/// Recover every identifiable member of a previously owned session.
pub fn kill_saved_session(leader: super::ChildIdentity) -> io::Result<()> {
    signal_members(leader, native_session, Signal::KILL).map(|_| ())
}

/// Recover a previously registered child. Its PID is either the session ID or
/// (for a legacy owner) the initial group ID. No numeric group signal is safe
/// once the original owner stopped reserving the leader's identity.
pub fn kill_saved_group(leader: super::ChildIdentity) -> io::Result<()> {
    signal_members(leader, native_group, Signal::KILL)?;
    kill_saved_session(leader)
}

fn signal_scope(leader: super::ChildIdentity, scope: &Scope, signal: Signal) -> io::Result<()> {
    if let Scope::Owner(owner) = scope {
        owner.tree.signal(leader, signal)?;
        #[cfg(target_os = "macos")]
        if super::is_alive(Some(leader))? {
            // Discover descendants before the signal can orphan them. The leader is
            // still our native child, whose unreaped PID cannot have been reused.
            vanished(
                rustix::process::kill_process(native_pid(leader.pid.get())?, signal)
                    .map_err(io::Error::from),
            )?;
        }
        return Ok(());
    }
    signal_leader_and_group(leader.pid, signal)?;
    let group = native_pid(leader.pid.get())?;
    signal_members(
        leader,
        |pid| {
            // The original group already received the signal; do not send its
            // members a second interrupt. Cleanup rescans all remaining members.
            let session = native_session(pid)?;
            if session == Some(group) && native_group(pid)? != Some(group) {
                Ok(session)
            } else {
                Ok(None)
            }
        },
        signal,
    )?;
    Ok(())
}

/// Signal the live members of the scope found in this pass, including members
/// in groups other than the leader's. The leader is checked again before each
/// signal so persisted IDs cannot target a subsequently reused scope.
fn signal_members(
    leader: super::ChildIdentity,
    membership: impl Fn(Pid) -> io::Result<Option<Pid>>,
    signal: Signal,
) -> io::Result<bool> {
    let owner = native_pid(leader.pid.get())?;
    let mut pids = process_ids()?;
    pids.sort_unstable_by_key(|pid| *pid == owner.as_raw_pid());
    let mut found = false;
    for pid in pids.into_iter().filter_map(Pid::from_raw) {
        if membership(pid)? != Some(owner) {
            continue;
        }
        let member = pid.as_raw_pid() as u32;
        let Some(start) = vanished(running_process_start_time(member))? else {
            continue;
        };
        if start < leader.start_time || (pid == owner && start != leader.start_time) {
            continue;
        }
        let same = || {
            Ok(membership(pid)? == Some(owner)
                && vanished(running_process_start_time(member))? == Some(start)
                && vanished(process_start_time(leader.pid.get()))?
                    .is_none_or(|start| start == leader.start_time))
        };
        found |= signal_member(pid, signal, same)?;
    }
    Ok(found)
}

#[cfg(target_os = "linux")]
fn signal_member(
    pid: Pid,
    signal: Signal,
    same: impl FnOnce() -> io::Result<bool>,
) -> io::Result<bool> {
    use rustix::process::{PidfdFlags, pidfd_open, pidfd_send_signal};
    let Some(file) = vanished(pidfd_open(pid, PidfdFlags::empty()).map_err(io::Error::from))?
    else {
        return Ok(false);
    };
    if same()? {
        return Ok(vanished(pidfd_send_signal(&file, signal).map_err(io::Error::from))?.is_some());
    }
    Ok(false)
}

#[cfg(not(target_os = "linux"))]
fn signal_member(
    pid: Pid,
    signal: Signal,
    same: impl FnOnce() -> io::Result<bool>,
) -> io::Result<bool> {
    // Darwin has no signal-by-process-handle API. Check membership and birth time
    // immediately before signalling only the observed member, never the whole PGID.
    if same()? {
        return Ok(
            vanished(rustix::process::kill_process(pid, signal).map_err(io::Error::from))?
                .is_some(),
        );
    }
    Ok(false)
}

#[cfg(not(target_os = "macos"))]
fn process_ids() -> io::Result<Vec<i32>> {
    let mut pids = Vec::new();
    for entry in std::fs::read_dir("/proc")? {
        let entry = entry?;
        if let Some(pid) = entry
            .file_name()
            .to_str()
            .and_then(|name| name.parse().ok())
        {
            pids.push(pid);
        }
    }
    Ok(pids)
}

#[cfg(target_os = "macos")]
fn process_ids() -> io::Result<Vec<i32>> {
    // Bound the same kernel enumeration cost as the existing group-cleanup query.
    const MAX_PID_BYTES: i32 = 16 * 1024 * 1024;
    // SAFETY: a null buffer asks libproc for the PID count without writing records.
    let count = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) };
    if count <= 0 {
        return Err(io::Error::last_os_error());
    }
    let bytes = count
        .checked_mul(std::mem::size_of::<i32>() as i32)
        .ok_or_else(|| io::Error::other("process enumeration size overflow"))?;
    if bytes > MAX_PID_BYTES {
        return Err(io::Error::other("process enumeration exceeds 16 MiB"));
    }
    let mut pids = vec![0; count as usize];
    // SAFETY: the aligned PID buffer has the queried byte capacity; truncation is rejected.
    let read = unsafe { libc::proc_listallpids(pids.as_mut_ptr().cast(), bytes) };
    if read < 0 {
        return Err(io::Error::last_os_error());
    }
    if read >= count {
        return Err(io::Error::other("incomplete process enumeration"));
    }
    pids.truncate(read as usize);
    Ok(pids)
}

fn signal_leader_and_group(leader: super::ProcessId, signal: Signal) -> io::Result<()> {
    let pid = native_pid(leader.get())?;
    // The original group may no longer contain the leader itself. It is still
    // our native child, whose unreaped PID cannot have been reused.
    let leader_result = if signal != Signal::KILL && native_group(pid)? == Some(pid) {
        Ok(())
    } else {
        vanished(rustix::process::kill_process(pid, signal).map_err(io::Error::from)).map(|_| ())
    };
    signal_owned_group(leader, signal).and(leader_result)
}

// For live ownership the leader is not reaped, including when we have observed its exit.
fn signal_owned_group(group: super::ProcessId, signal: Signal) -> io::Result<()> {
    match signal_group(native_pid(group.get())?, signal) {
        Ok(()) | Err(Errno::SRCH) => Ok(()),
        #[cfg(target_os = "macos")]
        Err(Errno::PERM) if process_group_exited(group.get())? => Ok(()),
        Err(error) => Err(error.into()),
    }
}

mod descriptors;
#[cfg(target_os = "linux")]
mod reaper;
#[cfg(target_os = "linux")]
mod subreaper;
mod tree;

// Observe actual OS-boundary signal attempts, not private Child fields.
fn signal_group(pgid: Pid, signal: Signal) -> Result<(), Errno> {
    #[cfg(test)]
    GROUP_SIGNALS.with(|count| count.set(count.get() + 1));
    rustix::process::kill_process_group(pgid, signal)
}

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

#[cfg(test)]
mod tests;