cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
//! Async spawn: a `::tokio::process::Command` over the sync spawn core via `as_std_mut`. Every
//! stdio end is ours: `resolve_into_std` makes the pipes as the sync spawn does and hands tokio's
//! `Command` only child ends, and the parent ends wait in the `Child` until an accessor registers
//! one with the reactor. Identity is read before any await, then attach (with error-path teardown).

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
use crate::child::spawn::build_std_command;
use crate::child::spawn::{resolve_identity, Classify, SpawnFailure};
use crate::command::Command;
use crate::error::{ChildFate, Error};
use crate::identity::Resolved;

use super::child::{Child, ProcSource};
#[cfg(unix)]
use crate::signal::Sent;

pub(crate) fn spawn(cmd: &mut Command) -> Result<Child, SpawnFailure> {
    spawn_uncommitted(cmd)?.commit_kill_on_drop()
}

/// [`spawn`] up to the handle it returns, whose containment resource still tears the tree down
/// on drop whatever `kill_on_drop` says.
///
/// Every failure says whether the program could have started; see [`SpawnFailure`].
pub(super) fn spawn_uncommitted(cmd: &mut Command) -> Result<Child, SpawnFailure> {
    // tokio's `process::Command::spawn` needs a running reactor; outside ANY runtime it panics on
    // Unix and defers the failure on Windows — reject that no-runtime case up front so it is a typed
    // Err on every platform.
    if ::tokio::runtime::Handle::try_current().is_err() {
        return Err(SpawnFailure::NotStarted(Error::Io(std::io::Error::other(
            "cosca::tokio::Command must be spawned from within a Tokio runtime",
        ))));
    }

    // Before anything is made or forked: a pidfd that is refused means no child, and no leaf.
    #[cfg(target_os = "linux")]
    crate::os_process::linux::open::probe_pidfd_support_with(&crate::identity::HostKernel).not_started()?;

    let kill_on_drop = cmd.kill_on_drop_flag();

    // Elevation runs before fds are taken (mirrors sync). POSIX rewrites into a derived command and
    // returns from the block below. On Windows an already-elevated caller falls through here with the
    // report the child carries.
    #[cfg(windows)]
    let mut elevation_report: Option<crate::elevation::ElevationReport> = None;
    if cmd.elevation_request().enabled {
        #[cfg(windows)]
        {
            use crate::elevation::windows::{launch_runas, RunasOutcome};
            match launch_runas(&*cmd)? {
                RunasOutcome::Launched {
                    proc,
                    granted,
                    id,
                    report,
                    pid,
                } => {
                    let raw = windows_raw::RawAsyncChild::new(proc, pid, granted);
                    let mut child = Child::from_parts(
                        ProcSource::Raw(raw),
                        Some(id),
                        kill_on_drop,
                        crate::containment::Attachment::uac_elevated(),
                        super::child::FdPipes::new(),
                    );
                    child.set_elevation(Some(report));
                    return Ok(child);
                }
                RunasOutcome::AlreadyElevated => {
                    elevation_report = Some(crate::elevation::already_elevated_report(
                        crate::elevation::ElevatedStdio::Passthrough,
                    ));
                    // fall through to the normal async spawn of the (already-elevated) cmd
                }
            }
        }
        #[cfg(unix)]
        {
            let mut rw = crate::elevation::posix::rewrite(cmd).not_started()?;
            let backend_path = rw.backend_path;
            // Remap an exec failure to BackendUnavailable only when the backend path is the culprit
            // (see the sync path).
            // From here the child is the backend: its elevated program may outlive what happens to it.
            let wrapper = rw.report.as_ref().is_some_and(|r| r.via.program_outlives_child());
            let spawned = (|| {
                let child = spawn_uncommitted(&mut rw.derived);
                let mut child = match backend_path.as_deref() {
                    Some(bp) => child.map_err(|f| f.map(|e| crate::elevation::remap_derived_spawn_error(e, bp)))?,
                    None => child?,
                };
                // Set the report BEFORE handling the deferred password: a cleanup kill() in the
                // write-failure path must see the elevated state so an EPERM maps to the typed
                // Unkillable rather than leaking a raw Io.
                child.set_elevation(rw.report);
                let written = rw.password_write.map_or(Ok(()), |pw| pw.write_after_spawn());
                finish_elevated(child, written)
            })();
            return spawned.map_err(|failure| if wrapper { failure.behind_wrapper() } else { failure });
        }
    }

    // Read the routing rule BEFORE the take, for the reason spelled out at
    // `crate::child::spawn::routes_to_raw_backend`: after it, a high-descriptor-only command
    // would take the std path and lose its descriptors in silence.
    #[cfg(windows)]
    let to_raw_backend = crate::child::spawn::routes_to_raw_backend(cmd);
    let fds = std::mem::take(cmd.fds_mut());

    // Route the cases tokio's `Command` cannot express to the raw `CreateProcessW` backend:
    // an `executable()` loaded independently of argv[0], OR arbitrary descriptors
    // (fd >= 3, wired through the MSVCRT `lpReserved2` table). The raw backend handles BOTH
    // contained and uncontained via its own async containment; everything else stays on
    // the std/tokio path, whose `prepare` applies containment for argv/commandline spawns.
    #[cfg(windows)]
    if to_raw_backend {
        // An elevated request never routes here: the Windows gate refuses `executable()`,
        // `raw_executable()` and fd >= 3 on it, already elevated or not.
        debug_assert!(
            elevation_report.is_none(),
            "an elevated request reached the raw backend past the gate"
        );
        return windows_raw::spawn_raw(cmd, fds, kill_on_drop);
    }

    #[cfg(unix)]
    let mut steps = crate::child::spawn::in_child::InChild::default();
    #[cfg(target_os = "linux")]
    let (std_cmd, handshake) =
        crate::child::spawn::build_std_command_with(cmd, &mut steps, crate::child::spawn::pidfd_handshake::register)
            .not_started()?;
    #[cfg(target_os = "macos")]
    let (std_cmd, report) =
        crate::child::spawn::build_std_command_with(cmd, &mut steps, crate::child::spawn::unique_report::register)
            .not_started()?;
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let std_cmd = build_std_command(cmd).not_started()?;
    let mut tcmd = ::tokio::process::Command::new(std::ffi::OsStr::new(""));
    *tcmd.as_std_mut() = std_cmd;
    // tokio's own `kill_on_drop` is intentionally left at its `false` default: cosca's
    // `Child::drop` is the SOLE owner of the kill, and it releases tokio's `Child` right after.
    // Forwarding the builder's `kill_on_drop` to `tcmd` would add a second, unsequenced kill
    // inside that release, where nothing orders it against the tree kill.

    let reserved = crate::child::spawn::reserved_fds(&fds);

    // The pidfd the handshake opens; the child keeps it (Linux).
    #[cfg(target_os = "linux")]
    let mut held_pidfd: Option<std::os::fd::OwnedFd> = None;

    // Phase 1 (before spawn): root detection + pre-spawn containment setup, whose in-child steps
    // join `steps`, which runs fd_map's dup2 LAST in the child (see the ordering rationale in
    // child/spawn.rs). On macOS the spawn lock is widened to enclose `prepare`
    // through `drop(tcmd)` — see child/spawn.rs's matching comment for the race this closes
    // (dropping `tcmd` here drops the inner `std::process::Command` it wraps, which is what
    // actually owns the marker write end's supervisor-side copy).
    #[cfg(target_os = "macos")]
    let (mut prepared, child, unique, parent_ends) = {
        let (mut prepared, spawned, first, parent_ends) = {
            let _guard = crate::child::spawn::spawn_lock();
            let parent_ends =
                crate::child::spawn::resolve_into_std(tcmd.as_std_mut(), &mut steps, &fds).not_started()?;
            let prepared = crate::containment::prepare(
                tcmd.as_std_mut(),
                &mut steps,
                &cmd.contain_request(),
                cmd.flags_request(),
                &reserved,
                cmd.fd_marker_suppressed(),
                cmd.env_ops(),
            )
            .not_started()?;
            let report = report.open(&_guard).not_started()?;
            steps.register(tcmd.as_std_mut());

            #[allow(
                clippy::disallowed_methods,
                reason = "spawn_lock is held by `_guard` at the top of this function"
            )]
            let (spawned, first) = report.run(
                || {
                    let spawned = tcmd.spawn();
                    #[cfg(test)]
                    let spawned = crate::child::spawn::fault::fail_tokio_spawn_after_fork(spawned);
                    spawned.map_err(Error::Io)
                },
                ::tokio::process::Child::id,
            );
            drop(tcmd);
            (prepared, spawned, first, parent_ends)
        };
        // Outside the lock, as the sync spawn does. It still blocks this thread: principle 2's spawn
        // exception.
        let unique = first.finish();
        let c = match spawned {
            Ok(c) => c,
            Err(e) => {
                let e = crate::child::spawn::unique_report::failed_spawn_error(e, &unique);
                // Without an id the program never ran, but who collected the child is open: a signal
                // after the refusal makes std return `Ok`, and tokio's own setup can then drop the
                // child unreaped. With an id, or a report that could not be read or was malformed,
                // the program may have run, and may still be running only if tokio's own setup failed
                // after std returned `Ok`: a std `Err` has already collected the child.
                use crate::child::spawn::unique_report::Report;
                use crate::containment::AbandonedChild;
                let front = cmd.elevation_front();
                let abandoned = match unique {
                    Report::ChildRefused(_) | Report::Missing => AbandonedChild::MaybeUnreaped,
                    // Not waited for: tokio's error took the pid. If tokio failed after std's `Ok`, the
                    // child may yet report and `exec`, with nothing holding it.
                    Report::Unwritten => AbandonedChild::MaybeUnreachable,
                    _ => prepared.abandon_before_verdict(front.is_some()),
                };
                // tokio's error does not say whether std's spawn failed, so only the report can prove
                // the program never ran.
                return Err(if crate::child::spawn::unique_report::proves_no_exec(&unique) {
                    warn_for_abandoned(&abandoned, &e, None);
                    SpawnFailure::NotStarted(e)
                } else {
                    abandoned_failure(abandoned, e, front)
                });
            }
        };
        (prepared, c, unique, parent_ends)
    };
    #[cfg(not(target_os = "macos"))]
    let (mut prepared, child, parent_ends) = {
        // Before `prepare`: a refused stdio fails before a cgroup leaf exists (Linux) and before
        // `prepare` mutates this process (Windows).
        let parent_ends = crate::child::spawn::resolve_into_std(
            tcmd.as_std_mut(),
            #[cfg(unix)]
            &mut steps,
            &fds,
        )
        .not_started()?;
        let mut prepared = crate::containment::prepare(
            tcmd.as_std_mut(),
            #[cfg(unix)]
            &mut steps,
            &cmd.contain_request(),
            cmd.flags_request(),
            &reserved,
            cmd.fd_marker_suppressed(),
            cmd.env_ops(),
        )
        .not_started()?;
        // Until `attach` takes the leaf, a failed spawn's teardown drops or abandons it here, and its
        // drain waits warn once past 1 s.
        #[cfg(target_os = "linux")]
        {
            prepared.teardown_warn_after = super::child::slow_teardown_after();
        }
        // A front this host could not place after a cgroup kill is refused before it is spawned.
        #[cfg(target_os = "linux")]
        if let Some(leaf) = prepared
            .cgroup_leaf
            .as_ref()
            .filter(|_| cmd.elevation_front().is_some())
        {
            crate::containment::cgroup::front_placement(&crate::identity::HostKernel, || leaf.id()).not_started()?;
        }

        // Serialize the spawn against the raw backend's inheritable-handle window via the shared
        // spawn lock: tokio's own handle-inheritance marking must not overlap a raw
        // `CreateProcessW` spawn on another thread (mirrors the sync std path). On Linux the lock
        // also spans the pidfd handshake's channel, from its creation to its helper's join.
        let _guard = crate::child::spawn::spawn_lock();

        // Linux: the child is held before `exec` until the parent holds the pidfd it sent, which
        // the child then keeps. Its hook was registered first of all, so the fd map, which may
        // `dup2` a mapping onto any number including the channel's, runs after the handshake is done.
        // Any child spawned for a cgroup leaf is left to the leaf when its spawn fails after its
        // fork, with the handshake's pidfd (see `Handshake::leaving_front`).
        #[cfg(target_os = "linux")]
        let left_pidfd = crate::child::spawn::pidfd_handshake::LeftPidfd::default();
        #[cfg(target_os = "linux")]
        let handshake = handshake
            .open(&_guard)
            .not_started()?
            .leaving_front(
                cmd.elevation_front(),
                prepared.cgroup_leaf.is_some().then(|| std::rc::Rc::clone(&left_pidfd)),
            )
            .warning_past(super::child::slow_teardown_after());
        // A root whose group is its containment, with no leaf to kill through: a spawn tokio fails after
        // its fork kills the group too.
        #[cfg(target_os = "linux")]
        let handshake = handshake.killing_group(prepared.leafless_group_is_containment());

        #[cfg(unix)]
        steps.register(tcmd.as_std_mut());

        let c = {
            // Classified at the SYSCALL — see the sync std path for why the whole spawn tree is
            // the wrong domain for this attribution.
            //
            // tokio can fail this spawn after its fork succeeded (its `build_child`: its pidfd
            // reaper, its signal driver), dropping the child neither killed
            // nor reaped, and it returns no pid. A cgroup leaf is still killed through when
            // `prepared` drops, since that needs no pid (see `cgroup`'s report contract). The
            // handshake's pidfd kills and reaps the child, and, on 6.9+, kills its process group
            // when that is its containment and no leaf holds it (`killing_group`).
            #[cfg(target_os = "linux")]
            let spawned = {
                #[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` above")]
                let held = handshake.run(|| {
                    let spawned = tcmd.spawn();
                    #[cfg(test)]
                    let spawned = crate::child::spawn::fault::fail_tokio_spawn_after_fork(
                        spawned,
                        prepared.cgroup_leaf.as_ref().map(|leaf| leaf.path()),
                    );
                    spawned
                });
                held.map(|held| {
                    held_pidfd = Some(held.pidfd);
                    held.child
                })
            };
            // Windows: tokio's error does not say whether `CreateProcess` failed, or tokio's own setup
            // after it.
            #[cfg(not(target_os = "linux"))]
            let spawned = {
                #[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` above")]
                let spawned = tcmd.spawn();
                #[cfg(test)]
                let spawned = crate::child::spawn::fault::fail_tokio_spawn_after_fork(spawned);
                let spawned = spawned.map_err(Error::Io);
                #[cfg(windows)]
                let spawned =
                    spawned.map_err(|e| crate::command::flags::classify_spawn_syscall_error(e, *cmd.flags_request()));
                spawned
            };
            match spawned {
                Ok(c) => c,
                Err(e) => {
                    // Whatever tokio did with the child, the leaf's exchange says what became of
                    // it; without a leaf, nothing can tell.
                    let front = cmd.elevation_front();
                    #[cfg(target_os = "linux")]
                    {
                        // Whatever tokio did with the child, the leaf's exchange says what became of
                        // it; the handshake already answered for a child it held, except one it
                        // left its pidfd for, which the leaf answers for.
                        let left = left_pidfd.take();
                        let left_to_leaf = left.is_some();
                        let abandoned = prepared.abandon_before_verdict(front.is_some(), left);
                        return Err(abandoned_after_handshake(abandoned, e, front, left_to_leaf));
                    }
                    // Windows: only the leaf's exchange could say what became of a child tokio
                    // dropped.
                    #[cfg(windows)]
                    {
                        let abandoned = prepared.abandon_before_verdict(front.is_some());
                        return Err(abandoned_failure(abandoned, e, front));
                    }
                }
            }
        };
        (prepared, c, parent_ends)
    };

    // Identity must be read before any await: spawn + attach are synchronous, so the runtime cannot
    // park and reap the child in between. The read is then checked through the backend's handle
    // (below), since on Unix nothing pins the pid against a foreign reap and reuse.
    let pid = child.id().expect("a freshly spawned, un-awaited tokio child has a pid");
    #[cfg(windows)]
    let proc_handle = child
        .raw_handle()
        .expect("a freshly spawned tokio child has a raw handle");
    // macOS: the unique id every by-pid signal to this child is checked against. Without one the
    // backend acts on the pid never, and the spawn fails below once the backend exists.
    #[cfg(target_os = "macos")]
    let (identity, not_adopted) = match crate::child::spawn::unique_report::adopted_id(unique, pid) {
        Ok(unique) => (Some(unique), None),
        // A late id still names the child, for its teardown.
        Err(not_adopted) => (
            match not_adopted.why {
                crate::child::spawn::unique_report::Unadoptable::Late(unique) => Some(unique),
                _ => None,
            },
            Some(not_adopted),
        ),
    };
    // Built first so failure arms tear the child down through its handle, not its pid. On macOS a
    // child with no adopted id is id-less, and the spawn fails below.
    #[cfg(target_os = "linux")]
    let proc = {
        // Before `child` moves into the backend: a panic here would drop tokio's `Child` by value.
        let held_pidfd = held_pidfd.expect("a spawned child holds the pidfd its handshake opened");
        ProcSource::new(child, pid, held_pidfd)
    };
    #[cfg(target_os = "macos")]
    let mut proc = ProcSource::new(child, pid, identity);
    #[cfg(windows)]
    let proc = ProcSource::new(child, pid);
    #[cfg(target_os = "macos")]
    if let Some(not_adopted) = not_adopted {
        #[cfg(test)]
        crate::child::spawn::fault::capture(crate::identity::ProcessId::of(pid));
        prepared.settle_verdict();
        use crate::child::spawn::unique_report::Unadoptable;
        let error = not_adopted.error;
        let left = crate::child::spawn::FrontFate::LeftUnreaped;
        let front = cmd.elevation_front();
        return Err(match not_adopted.why {
            Unadoptable::DiedBeforeExec => {
                // Only a corpse is left, and tokio's `Child` must not reap it by pid.
                proc.forget_because("died before exec");
                SpawnFailure::NotStarted(error)
            }
            // An elevation front is sent nothing: forgotten and left unreaped, as for an unverified one.
            Unadoptable::Late(_) if front.is_some() => {
                proc.leave_late_front(pid);
                SpawnFailure::started(
                    left.note(error, front, Some(pid)),
                    ChildFate::Running { id: None },
                    None,
                )
            }
            // Its id came late: torn down through it, as the sync spawn does.
            Unadoptable::Late(unique) => {
                SpawnFailure::started(error, proc.reap_unreported(pid, unique, prepared), None)
            }
            // An elevation front is sent nothing and handed to no reaper: left unreaped, as the sync
            // spawn leaves it, and the error says so.
            Unadoptable::Unverified if front.is_some() => {
                proc.forget_because("is an elevation front, sent nothing, and left unreaped");
                SpawnFailure::started(
                    left.note(error, front, Some(pid)),
                    ChildFate::Running { id: None },
                    None,
                )
            }
            // With no id the backend neither signals nor waits by pid: the child is forgotten, with
            // a warning naming it, and left running.
            Unadoptable::Unverified => SpawnFailure::started(error, proc.reap_now(pid, None), None),
        });
    }
    // The pidfd the handshake opened, which the backend just built holds. Were it ever gone, the child
    // is torn down as an unverifiable one: no panic after the fork.
    #[cfg(target_os = "linux")]
    let Some(handle) = proc.child_handle(pid) else {
        debug_assert!(false, "a freshly spawned tokio child holds its pidfd");
        let fate = proc.reap_now(pid, None);
        return Err(SpawnFailure::started(
            crate::child::spawn::spawn_identity_error(Resolved::Unknown, Default::default()),
            fate,
            None,
        ));
    };
    #[cfg(test)]
    crate::child::spawn::fault::run_at(crate::child::spawn::fault::SpawnPoint::BeforeIdentity, pid);
    #[cfg(unix)]
    let front = cmd.elevation_front();
    // A front's leaf subtree, captured while it exists: a failure arm drops the leaf, killing it.
    #[cfg(target_os = "linux")]
    let subtree = crate::child::spawn::front_subtree(front.and(prepared.cgroup_leaf.as_ref()));
    #[cfg(unix)]
    if front.is_some() {
        prepared.watch_front(pid);
    }
    // The handle checks the read: a pid alone does not say whom it names once something else has
    // reaped the child. The backend exists already, so a failure here tears the child down through
    // it, and a panic unwinds through `ProcSource`'s `Drop`. The attach below takes this identity
    // and does not re-read the root's.
    let (resolved, cause, mut why) = match proc.target() {
        Some(through) => resolve_identity(&crate::identity::HostKernel, pid, &through),
        // Contract: a freshly spawned child holds its handle on every platform.
        None => {
            debug_assert!(false, "a freshly spawned tokio child holds its handle");
            (
                Resolved::Unknown,
                Default::default(),
                crate::child::spawn::Diagnosis::default(),
            )
        }
    };
    let id = match resolved {
        Resolved::Found(id) => Ok(id),
        // Kept with no identity; see `Child::id`.
        Resolved::Unknown => Err(crate::child::spawn::kept_without_identity(pid, cause, &mut why)),
        // Tear the child down so a vanished-identity error never leaks a live (Windows: still
        // CREATE_SUSPENDED) process.
        other => {
            // Settle the leaf's verdict before any kill, so the kill never races its reads.
            crate::child::spawn::settle_before_teardown(
                &mut prepared,
                #[cfg(target_os = "linux")]
                handle,
            );
            // An elevation front is sent nothing (see `ProcSource::leave_front`). Its containment
            // goes first: a cgroup leaf's drop kills it, so the teardown waits for a contained front
            // that kill reached, and says what became of it.
            #[cfg(unix)]
            if let Some(front) = front {
                #[cfg(target_os = "linux")]
                drop(prepared);
                // macOS: a front found gone is left unverified, as the sync spawn leaves it.
                #[cfg(target_os = "macos")]
                let (fate, child_fate) = leave_unverified_front(&mut proc, &mut why);
                #[cfg(target_os = "macos")]
                return Err(SpawnFailure::started(
                    fate.note(
                        crate::child::spawn::spawn_identity_error(other, cause),
                        Some(front),
                        Some(pid),
                    ),
                    child_fate,
                    None,
                ));
                #[cfg(not(target_os = "macos"))]
                {
                    let (error, child_fate) = proc.leave_front_noting(
                        pid,
                        None,
                        subtree.as_ref(),
                        &mut why,
                        crate::child::spawn::spawn_identity_error(other, cause),
                        front,
                    );
                    return Err(SpawnFailure::started(error, child_fate, None));
                }
            }
            // Linux 6.9+: the group the root may have left members in, whoever reaped the root.
            #[cfg(target_os = "linux")]
            crate::child::spawn::kill_group_before_teardown(&prepared, handle, &mut why);
            // macOS: nothing kills the group, which the teardown's one warn says.
            #[cfg(target_os = "macos")]
            crate::child::spawn::note_group_left_running(&prepared, pid, &mut why);
            let child_fate = proc.reap_now_noting(pid, None, &mut why);
            return Err(SpawnFailure::started(
                crate::child::spawn::spawn_identity_error(other, cause),
                child_fate,
                None,
            ));
        }
    };
    #[cfg(test)]
    crate::child::spawn::fault::run_at(crate::child::spawn::fault::SpawnPoint::BeforeAttach, pid);
    // What the attach does not consume of the identity read: what the child becomes, and what the
    // failure arms tear down by.
    let id_read = id.as_ref().ok().copied();
    let attach = crate::child::spawn::attach_or_fault(
        #[cfg(unix)]
        pid,
        id,
        #[cfg(target_os = "linux")]
        handle,
        #[cfg(windows)]
        proc_handle,
        prepared,
    );
    let attachment = match attach {
        Ok(v) => v,
        Err(error) => {
            #[cfg(target_os = "macos")]
            if id_read.is_some() {
                crate::child::spawn::assert_attach_cannot_fail(&error);
            }
            #[cfg(unix)]
            if let Some(front) = front {
                // macOS: a front is sent nothing and left unreaped, as the sync spawn leaves it.
                #[cfg(target_os = "macos")]
                let (fate, child_fate) = {
                    proc.forget_because("is an elevation front whose attach failed, sent nothing, and left unreaped");
                    (
                        crate::child::spawn::FrontFate::LeftUnreaped,
                        ChildFate::Running { id: id_read },
                    )
                };
                // Elsewhere the failed attach has dropped the containment: a cgroup leaf's drop kills
                // and drains it, so a front in it is dying, and is waited for.
                #[cfg(not(target_os = "macos"))]
                {
                    let (error, child_fate) =
                        proc.leave_front_noting(pid, id_read, subtree.as_ref(), &mut why, error, front);
                    return Err(SpawnFailure::started(error, child_fate, None));
                }
                #[cfg(target_os = "macos")]
                return Err(SpawnFailure::started(
                    fate.note(error, Some(front), Some(pid)),
                    child_fate,
                    None,
                ));
            }
            // macOS: killed and reaped through its verified unique id, as the sync spawn does, and
            // tokio's `Child` forgotten: its drop reaps by pid.
            #[cfg(target_os = "macos")]
            let child_fate = {
                let fate = crate::child::spawn::kill_and_reap_verified(
                    pid,
                    identity.expect("a spawn that reached the attach adopted its unique id"),
                    id_read,
                    &format!("is {}", crate::tokio::child::HANDED_TO_ORPHAN_REAPER),
                    crate::tokio::child::slow_teardown_after(),
                );
                // A child its kill did not end is released to tokio's orphan reaper, not forgotten, which
                // would leave a zombie nothing collects.
                if matches!(fate, ChildFate::Running { .. }) {
                    proc.release();
                } else {
                    proc.forget_because("is a child whose attach failed, killed through its verified unique id");
                }
                fate
            };
            // The child is spawned (on Windows possibly CREATE_SUSPENDED) - tear it down so a failed
            // attach never leaks a live/suspended process.
            #[cfg(not(target_os = "macos"))]
            let child_fate = proc.reap_now_noting(pid, id_read, &mut why);
            return Err(SpawnFailure::started(error, child_fate, None));
        }
    };

    let mut child = Child::from_parts(proc, id_read, kill_on_drop, attachment, parent_ends);
    #[cfg(windows)]
    child.set_elevation(elevation_report);
    child.set_front(cmd.elevation_front());
    Ok(child)
}

/// macOS: a front whose identity read found it reaped elsewhere (`Gone`) is left unverified, as the
/// sync spawn's `leave_unverified_child` leaves any child: sent nothing, and tokio's `Child`
/// forgotten, since its drop reaps by pid.
#[cfg(target_os = "macos")]
fn leave_unverified_front(
    proc: &mut ProcSource,
    why: &mut crate::child::spawn::Diagnosis,
) -> (crate::child::spawn::FrontFate, ChildFate) {
    proc.forget_noting("was reaped by someone else", super::child::Forgotten::Unproven, why);
    (
        crate::child::spawn::FrontFate::of_unverified(crate::containment::RootIdentity::Gone),
        ChildFate::Gone,
    )
}

/// Async twin of the sync `finish_elevated` (see there). The root's reap is blocking (`try_wait`
/// cannot reap a just-killed child, so it would leak a zombie), and waits only on this kill. The
/// front's gate is decided once, before the tree's kill. The backend has run, so the program may
/// have started. The waits for the root and for the tree's drain each warn once past 1 s.
#[cfg(unix)]
pub(crate) fn finish_elevated(mut child: Child, written: Result<(), Error>) -> Result<Child, SpawnFailure> {
    use crate::containment::dispatch::{SettleOutcome, TreeKillOutcome};

    let Err(write_err) = written else {
        return Ok(child);
    };
    // A live front outside a cgroup is not signalled, by its group or otherwise: the root's kill
    // below then says why.
    let gate = child.kill_gate();
    // The look at the root, right before the tree kill it decides.
    let view = child.read_root_view(crate::containment::dispatch::TeardownCaller::FinishElevated);
    // What forgetting tokio's `Child` leaked, if the cleanup forgot it: the one warn below says so.
    let mut forgot: Option<crate::child::drop_report::Forgot> = None;
    let mut skipped = None;
    let front_closed = matches!(gate, crate::elevation::front::Gate::Closed(_));
    let exited_front = matches!(gate, crate::elevation::front::Gate::Exited);
    // The drain watch's failure after a kill that landed: its own fact, beside the kill's outcome.
    let mut drain_failure = None;
    let tree: Option<TreeKillOutcome> = (child.containment().can_teardown() && !front_closed).then(|| {
        let kill = child.kill_tree_members_unless_reaped(&view);
        skipped = kill.skip_note(&view);
        // Unlike `Drop`, this path may block. Waiting for the drain here lets the handle's drop
        // remove the leaf on its first `rmdir` instead of leaving it behind with a warning
        // naming a `wait_tree` the caller never gets.
        if kill.completed() {
            drain_failure = child.block_until_members_drained().err();
        }
        kill
    });
    let tree_failure = tree.as_ref().and_then(TreeKillOutcome::incomplete);
    // The root is settled when it is gone (killed and reaped, or reaped by someone else) or was
    // deliberately not signalled (an unpinned root, a live front). A refused kill leaves it to the
    // handle's drop to try again.
    let mut root_settled = true;
    let (root_note, fate) = if view.unpinned_root() {
        forgot = child.forget_for(&view);
        // Nothing was signalled.
        let fate = crate::os_process::child::Foreign::Gone.fate(false);
        (
            format!(
                "the elevated child was left alone, neither signalled nor waited on: {}",
                view.why_number_untrusted()
            ),
            fate,
        )
    } else {
        let root = match gate {
            // Not asked again after the kill: a killed front can read as neither exited nor in its
            // cgroup, between leaving the cgroup's member list and becoming a zombie.
            // The kill's own outcome says it landed; the handle's state is settled by `settle`, below.
            crate::elevation::front::Gate::CgroupOnly if tree.as_ref().is_some_and(TreeKillOutcome::completed) => {
                child.cgroup_kill_reached().map(|()| Sent::Delivered)
            }
            // No kill reached the cgroup: refused as `kill` refuses, naming why.
            crate::elevation::front::Gate::CgroupOnly => Err(child.cgroup_not_killed(tree_failure.as_deref())),
            crate::elevation::front::Gate::Closed(unkillable) => Err(unkillable),
            gate @ (crate::elevation::front::Gate::Open | crate::elevation::front::Gate::Exited) => {
                child.signal_gated("kill", gate)
            }
        };
        // A child that is gone, or not verified to be ours, is forgotten here, not by the kill: tokio's
        // wait and drop reap by pid.
        if matches!(root, Ok(Sent::Gone | Sent::Unverified)) {
            forgot = child.forget_for(&view);
        }
        match root {
            Ok(Sent::Delivered) => {
                let (fate, forgotten) = child.wait_and_reap_blocking();
                forgot = forgotten;
                let note = if exited_front {
                    "the elevated child had already exited, and was reaped"
                } else {
                    "the elevated child was terminated"
                };
                (note.to_string(), fate)
            }
            // Reaped by someone else: nothing was terminated, and nothing is waited on by its number,
            // which may name another process by now.
            Ok(Sent::Gone) if exited_front => (
                "the elevated child had already exited, and was reaped by someone else".to_string(),
                ChildFate::Gone,
            ),
            Ok(Sent::Gone) => (
                "the elevated child could not be terminated (it was already reaped by someone else)".to_string(),
                ChildFate::Gone,
            ),
            // Nothing could be verified to signal: the child may still be running.
            Ok(Sent::Unverified) => {
                root_settled = false;
                (
                    "the elevated child could not be terminated (it could not be verified, and may still be running)"
                        .to_string(),
                    ChildFate::Running { id: child.id() },
                )
            }
            Err(e) => {
                root_settled = front_closed;
                // The `try_wait` reaps by pid: a child the handle shows reaped elsewhere is forgotten.
                forgot = child.forget_for(&view);
                let id = child.id();
                let fate = match &forgot {
                    Some(forgot) if forgot.reaped_elsewhere() => ChildFate::Gone,
                    Some(_) => ChildFate::Running { id },
                    None => crate::child::spawn::fate_of_a_look(child.try_wait().map_err(|e| e.raw_os_error()), id),
                };
                (
                    format!("the elevated child {}", crate::child::owned::teardown::kill_refused(&e)),
                    fate,
                )
            }
        }
    };
    let tree = tree.map(|walk| child.settle_tree(walk, fate.not_running()));
    // The tree is settled when no kill of it is left to try and its drain was watched, or it was
    // deliberately left alone because the root is reaped or unpinned. A drain that could not be watched
    // leaves the handle armed: its drop waits for it again. (A drain is watched only after a kill that
    // `settle` answers `Killed`, so a failed watch is never over an unvouched tree.)
    let tree_settled = (!crate::child::spawn::tree_needs_another_kill(&tree) && drain_failure.is_none())
        || (skipped.is_some() && view.leaves_root_alone());
    let unvouched = matches!(tree, Some(Ok(SettleOutcome::Unvouched { .. })));
    // An unvouched tree disarms the handle on the strength of the root's end: nothing is left for the
    // drop to kill.
    debug_assert!(
        !(unvouched && root_settled) || fate.not_running(),
        "an unvouched tree leaves the handle disarmed only over a root that ended: {fate:?}"
    );
    let subject = child.teardown_subject();
    let (mut tree_note, tree_warn) = crate::child::spawn::report_tree_teardown(tree, &subject);
    // A drain is watched only after a kill that left nothing, which `settle` answers `Killed`.
    debug_assert!(
        drain_failure.is_none() || tree_warn.is_none(),
        "a drain watch failed after a kill that is reported as failed"
    );
    let drain_warn = drain_failure.as_ref().map(|drain| {
        tree_note.push_str(&format!(
            "; its contained tree was killed, but its drain could not be watched ({subject}: {drain}); the handle \
             stays armed to watch it again"
        ));
        crate::child::spawn::tree_teardown_warn(
            &subject,
            &format_args!("the kill succeeded, but its drain could not be watched ({drain})"),
        )
    });
    if let Some(note) = skipped {
        tree_note.push_str(&format!("; its contained tree was not killed: {note}"));
    }
    let mut report = crate::child::drop_report::DropReport::new(&view);
    report.forgot = forgot;
    report.tree = tree_warn;
    report.drain = drain_warn;
    let warned = report.emit(&[]);
    child.end_cleanup(tree_settled && root_settled, warned);
    Err(SpawnFailure::started(
        Error::Elevation {
            kind: crate::error::ElevationErrorKind::AuthFailed,
            detail: format!("{write_err}; {root_note}{tree_note}"),
        },
        fate,
        None,
    ))
}

/// tokio reaps its child by pid, on drop or from its orphan queue; the handshake leaves that reap to
/// it, and only makes it happen while the number is still the child's.
#[cfg(target_os = "linux")]
impl crate::child::spawn::pidfd_handshake::Spawned for ::tokio::process::Child {
    const ERR_PROVES_NO_EXEC: bool = false;

    fn pid(&self) -> Option<u32> {
        self.id()
    }

    /// Waits through the pidfd until the child is a zombie, then has tokio reap it at once.
    fn reap_unexecuted(mut self, pidfd: std::os::fd::OwnedFd, warn_after: Option<std::time::Duration>) -> ChildFate {
        // Read first: tokio forgets the pid once `try_wait` has reaped.
        let pid = self.id();
        let delivered = crate::child::spawn::pidfd_handshake::await_unexecuted_exit(&pidfd, pid, warn_after);
        match self.try_wait() {
            Ok(Some(_)) => ChildFate::Reaped,
            // Killed, and its zombie not yet visible here (the wait for it failed, so a tracer may
            // hold it): tokio's drop hands it to its orphan queue.
            Ok(None) => {
                log::debug!(
                    "{}: not yet collectable; left to tokio's reaper",
                    crate::child::spawn::named(pid)
                );
                ChildFate::Killed
            }
            Err(e) => {
                log::debug!("{}: reaped by someone else ({e})", crate::child::spawn::named(pid));
                crate::os_process::child::Foreign::Gone.fate(delivered)
            }
        }
    }

    /// tokio reaps it, on drop or from its orphan queue.
    fn abandon_unreported(self, why: &str) {
        log::debug!(
            "{}: {why}; left to tokio's reaper",
            crate::child::spawn::named(self.id())
        );
    }
}

#[cfg(windows)]
#[path = "spawn/windows_raw.rs"]
pub(crate) mod windows_raw;

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

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/placement_reuse_tests.rs"]
mod placement_reuse_tests;

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/pidfd_tests.rs"]
mod pidfd_tests;

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/slow_teardown_tests.rs"]
mod slow_teardown_tests;

#[cfg(all(test, target_os = "macos"))]
#[path = "spawn/slow_teardown_macos_tests.rs"]
mod slow_teardown_macos_tests;

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/identity_group_tests.rs"]
mod identity_group_tests;

#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/post_fork_group_tests.rs"]
mod post_fork_group_tests;

#[cfg(all(test, windows))]
#[path = "spawn/slow_teardown_windows_tests.rs"]
mod slow_teardown_windows_tests;

/// The fate of a child a failed tokio spawn abandoned with no handle on it (see
/// [`warn_for_abandoned`]). Linux's handshake holds a pidfd on it, and answers itself.
///
/// Off Linux nothing is known of such a child, because only a Linux cgroup leaf says more than
/// `MaybeUnreachable`, and the spawn answers the other two itself, so they are a contract breach
/// that claims nothing.
#[cfg(not(target_os = "linux"))]
fn abandoned_fate(child: crate::containment::AbandonedChild) -> ChildFate {
    use crate::containment::AbandonedChild;

    match child {
        AbandonedChild::Ended(_) | AbandonedChild::MaybeUnreaped | AbandonedChild::Uncollected(_) => {
            debug_assert!(false, "only a Linux cgroup leaf abandons a child as `{child:?}`");
            ChildFate::Unknown
        }
        AbandonedChild::Front(fate) => {
            debug_assert!(false, "only a Linux cgroup leaf finds an abandoned front");
            front_child_fate(fate)
        }
        AbandonedChild::MaybeUnreachable => ChildFate::Running { id: None },
    }
}

/// Say what a failed tokio spawn may have left behind of its child: nothing, a zombie nothing
/// reaps, or a process nothing can reach.
///
/// tokio can fail a spawn after its fork, dropping the child neither killed nor reaped and
/// returning no pid. Only a cgroup leaf still reaches such a child, and only once the child has
/// told it who it is. The error cannot tell a failure before the fork from one after it, hence
/// "may". Reported at `warn` every time, unless `ended` says the child is gone.
///
/// `ended`: the handshake killed and reaped the child through its pidfd, or found it reaped. The
/// child is then not at risk, so its fate is logged at `debug`. The fate of an elevation `front` the
/// leaf found is noted on the error instead, as the spawn's other failures note it. A child the
/// leaf's pidfd reached and its teardown left uncollected says so, in the teardown's clause, under
/// the failed spawn's label. The warn is logged through
/// [`Left::warn`](crate::child::owned::teardown::Left::warn).
fn warn_for_abandoned(child: &crate::containment::AbandonedChild, error: &Error, ended: Option<ChildFate>) {
    use crate::containment::AbandonedChild;

    let consequence = match (child, ended) {
        (AbandonedChild::Front(_) | AbandonedChild::Ended(_), _) => return,
        (AbandonedChild::Uncollected(left), _) => {
            let by = crate::containment::dispatch::TeardownCaller::FailedSpawn.label();
            left.warn(&format!("tokio spawn failed ({error}); {by}: {}", left.clause));
            return;
        }
        (AbandonedChild::MaybeUnreaped | AbandonedChild::MaybeUnreachable, Some(fate)) => {
            log::debug!("tokio spawn failed ({error}); {fate}");
            return;
        }
        (AbandonedChild::MaybeUnreaped, None) => {
            "the child exits before `exec`; unless its spawn collected it, it may be left unreaped, since it \
             never reached the point where it names itself and nothing here holds its pid"
        }
        (AbandonedChild::MaybeUnreachable, None) => {
            "unless its spawn collected it, the child may be left running and nothing \
             can reach it: only a cgroup v2 leaf is killed without the child's pid"
        }
    };
    log::warn!("tokio spawn failed ({error}); if it failed after forking, {consequence}");
}

/// Warns of a tokio spawn that failed for a child never told to go and dropped with nothing holding
/// it: it never ran the program, and only its reaping is open. tokio's error took its pid, so none
/// is named.
#[cfg(target_os = "linux")]
fn warn_for_unreaped(error: &Error) {
    log::warn!(
        "tokio spawn failed ({error}); if it failed after forking, the child never ran the program, but it may \
         be left unreaped: nothing here holds its pid, and cosca never reaps a Linux child by pid"
    );
}

/// The fate of an elevation front the leaf's abandonment found: reaped through the leaf, left
/// running, or in a place that could not be read.
fn front_child_fate(fate: crate::child::spawn::FrontFate) -> ChildFate {
    use crate::child::spawn::FrontFate;

    match fate {
        FrontFate::Reaped => ChildFate::Reaped,
        FrontFate::LeftUnreaped => ChildFate::Running { id: None },
        FrontFate::Unaccounted | FrontFate::Unplaced => ChildFate::Unknown,
    }
}

/// The failure of a tokio spawn that left a child with no handle on it (Windows, macOS): the program
/// may have started, and `abandoned` says what became of the child. A front the leaf found notes
/// its fate on the error.
#[cfg(not(target_os = "linux"))]
fn abandoned_failure(
    abandoned: crate::containment::AbandonedChild,
    error: Error,
    front: Option<crate::elevation::front::Front>,
) -> SpawnFailure {
    warn_for_abandoned(&abandoned, &error, None);
    match abandoned {
        crate::containment::AbandonedChild::Front(fate) => {
            SpawnFailure::started(fate.note(error, front, None), front_child_fate(fate), None)
        }
        other => SpawnFailure::started(error, abandoned_fate(other), None),
    }
}

/// The failure of a Linux tokio spawn once its leaf's abandonment ran. The handshake already
/// answered, and tore down any child it held; only a child whose pidfd it left the leaf
/// (`left_to_leaf`) was left to the leaf, whose abandonment answers for it.
#[cfg(target_os = "linux")]
fn abandoned_after_handshake(
    abandoned: crate::containment::AbandonedChild,
    failure: SpawnFailure,
    front: Option<crate::elevation::front::Front>,
    left_to_leaf: bool,
) -> SpawnFailure {
    use crate::containment::AbandonedChild;

    // Except for a child left to the leaf, the handshake held the child; `ended_child` says whether
    // it ended it.
    let ended = failure.ended_child().filter(|_| !left_to_leaf);
    match abandoned {
        // The child was never told to go: it never ran the program, and only its reaping is open.
        AbandonedChild::MaybeUnreachable if failure.left_child_unreaped() => warn_for_unreaped(failure.error()),
        _ => warn_for_abandoned(&abandoned, failure.error(), ended),
    }
    if !left_to_leaf {
        return failure;
    }
    failure.answered_by(|error| match abandoned {
        AbandonedChild::Front(fate) => (fate.note(error, front, None), front_child_fate(fate)),
        // Out of the leaf's reach, and not known to be dead.
        AbandonedChild::MaybeUnreachable => (error, ChildFate::Running { id: None }),
        // What the teardown established of the child it left, or collected.
        AbandonedChild::Uncollected(left) => (error, left.remains.fate),
        AbandonedChild::Ended(fate) => (error, fate),
        AbandonedChild::MaybeUnreaped => (error, ChildFate::Unknown),
    })
}