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
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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
//! Windows Job Object containment: the root spawns suspended into a new console
//! group, is immediately assigned to a `KILL_ON_JOB_CLOSE` job, then resumed.
//! The kernel enforces the invariant: every descendant of the child inherits the
//! job (Windows jobs nest, so inner jobs are not a problem), and closing the job
//! handle terminates the whole tree.
//!
//! Kill-group race invariant (why `CREATE_SUSPENDED`):
//! the child must be inside the job before executing any instruction — otherwise
//! a fast-forking grandchild can escape the job before assignment completes.
//! Suspending the initial thread closes the race: assign the job while the child
//! is frozen, then resume so it can run.

use std::ffi::c_void;
use std::io;
use std::mem::size_of;
use std::sync::RwLock;

use windows::Win32::Foundation::{
    CloseHandle, SetHandleInformation, HANDLE, HANDLE_FLAGS, HANDLE_FLAG_INHERIT, WAIT_FAILED, WAIT_OBJECT_0,
    WAIT_TIMEOUT,
};
use windows::Win32::System::Console::{GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE};
use windows::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation,
    QueryInformationJobObject, SetInformationJobObject, TerminateJobObject, JOBOBJECT_BASIC_PROCESS_ID_LIST,
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
use windows::Win32::System::Threading::{
    GetProcessId, GetProcessIdOfThread, OpenProcess, OpenThread, ResumeThread, WaitForMultipleObjects,
    WaitForSingleObject, CREATE_NEW_PROCESS_GROUP, CREATE_SUSPENDED, PROCESS_QUERY_LIMITED_INFORMATION,
    PROCESS_SYNCHRONIZE, THREAD_QUERY_LIMITED_INFORMATION, THREAD_SUSPEND_RESUME,
};

use crate::error::{io_context, win32_io_error};

/// Sentinel: a null pointer means the handle has been consumed or is invalid.
fn null_ptr() -> *mut c_void {
    std::ptr::null_mut()
}

/// Owns the Job Object handle. `KILL_ON_JOB_CLOSE` means the whole process tree
/// is terminated when this handle is closed (dropped or explicitly killed).
///
/// Interior mutability allows `hard_kill` and `disarm` to be called via `&self`
/// (required because `Child::kill_tree` takes `&self`).
///
/// The lock is load-bearing, not incidental. Every use is "read the handle, then call
/// Win32 with it", and an atomic makes only the read indivisible — leaving a window in
/// which a concurrent `hard_kill`/`Drop` closes the handle before the call lands. Windows
/// recycles closed handle values onto unrelated kernel objects, so that call would then
/// operate on someone else's object: `disarm` writing a cleared `KILL_ON_JOB_CLOSE` to an
/// unrelated job silently leaves *its* tree to outlive its owner. Holding the lock across
/// the call is what makes load-then-use a single step.
pub(crate) struct JobHandle {
    /// The raw HANDLE value. Null means the handle has been consumed (taken/killed).
    raw: RwLock<*mut c_void>,
}

// A Windows job-object HANDLE is a process-wide kernel handle; using it
// (TerminateJobObject / CloseHandle) from another thread is sound because the
// kernel serialises job operations. The raw pointer inside `HANDLE` is otherwise
// `!Send`, which would prevent this type from crossing thread boundaries.
unsafe impl Send for JobHandle {}

// SAFETY: the pointer is only ever read or replaced under `raw`'s lock, which is what makes
// load-then-use indivisible; the job operations themselves are serialised by the kernel. This
// is required rather than incidental: `Job` is public, its methods take `&self`, and callers
// may share it across threads.
unsafe impl Sync for JobHandle {}

impl std::fmt::Debug for JobHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JobHandle").field("raw", &self.peek()).finish()
    }
}

impl JobHandle {
    fn new(handle: HANDLE) -> Self {
        debug_assert!(!handle.0.is_null(), "job handle must not be null");
        JobHandle {
            raw: RwLock::new(handle.0),
        }
    }

    /// The raw value, for diagnostics only — never to call Win32 with. Use [`with_handle`].
    fn peek(&self) -> *mut c_void {
        *self.raw.read().unwrap_or_else(|e| e.into_inner())
    }

    /// Run `f` with the live job handle, holding the lock so it cannot be closed and its
    /// value recycled underneath the call. `None` once consumed.
    ///
    /// Keep `f` short and non-blocking: it holds off `hard_kill` and `Drop` for its duration.
    /// A long wait must duplicate the handle inside `f` and then wait on the duplicate.
    pub(crate) fn with_handle<R>(&self, f: impl FnOnce(HANDLE) -> R) -> Option<R> {
        let guard = self.raw.read().unwrap_or_else(|e| e.into_inner());
        if guard.is_null() {
            None
        } else {
            Some(f(HANDLE(*guard)))
        }
    }

    /// Take the raw handle, leaving null. Returns `None` if already consumed.
    fn take(&self) -> Option<HANDLE> {
        let mut guard = self.raw.write().unwrap_or_else(|e| e.into_inner());
        let p = std::mem::replace(&mut *guard, null_ptr());
        if p.is_null() {
            None
        } else {
            Some(HANDLE(p))
        }
    }

    /// Terminate every process in the job, then close the handle.
    ///
    /// Returns the `TerminateJobObject` failure rather than only logging it: a caller that is
    /// told teardown succeeded while the tree is still running has no way to notice, and the
    /// other containment mechanisms already report this.
    pub(crate) fn hard_kill(&self) -> io::Result<()> {
        let Some(job) = self.take() else { return Ok(()) };
        // SAFETY: job is a valid handle we own; Win32 calls are safe.
        unsafe {
            let terminated = TerminateJobObject(job, 1).map_err(win32_io_error);
            if let Err(e) = CloseHandle(job) {
                log::warn!("CloseHandle on the job failed ({e}); the handle is leaked");
            }
            terminated
        }
    }

    /// Clear `KILL_ON_JOB_CLOSE` so closing this handle does NOT kill the tree.
    /// Called by `Child::detach()` before the handle is released: otherwise
    /// dropping the job handle terminates the tree the caller intended to keep alive.
    ///
    /// Returns the `SetInformationJobObject` failure, with the plain Win32 code: the flag is then
    /// still set, and closing this handle still kills the tree. A consumed handle has nothing to
    /// clear, and is `Ok`.
    pub(crate) fn disarm(&self) -> io::Result<()> {
        // Held across the call: this WRITES to the handle, so landing on a recycled value
        // would clear KILL_ON_JOB_CLOSE on an unrelated job and quietly let its tree
        // outlive its owner.
        self.with_handle(|job| {
            // A zeroed JOBOBJECT_EXTENDED_LIMIT_INFORMATION has LimitFlags == 0, which
            // clears KILL_ON_JOB_CLOSE.
            let info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
            // SAFETY: job is a valid handle; info is fully initialised (zeroed by default()).
            unsafe {
                SetInformationJobObject(
                    job,
                    JobObjectExtendedLimitInformation,
                    std::ptr::addr_of!(info).cast(),
                    size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
                )
            }
            .map_err(win32_io_error)
        })
        .unwrap_or(Ok(()))
    }
}

#[cfg(all(windows, test))]
impl JobHandle {
    /// Test-only: read the handle without holding the lock across its use.
    ///
    /// Reintroduces the load-then-use gap that [`with_handle`](JobHandle::with_handle) exists
    /// to close, so it is confined to tests, which do not race their own teardown.
    pub(crate) fn as_handle(&self) -> Option<HANDLE> {
        let p = self.peek();
        if p.is_null() {
            None
        } else {
            Some(HANDLE(p))
        }
    }

    /// Test-only: a real but empty job object (no process assigned). Cheap to create and
    /// cleanly closed on `Drop`; for variant-level assertions like
    /// `Attached::JobObject(_).is_actionable()`.
    pub(crate) fn create_empty_for_test() -> JobHandle {
        // Safety: CreateJobObjectW with null name/attrs returns an owned job handle.
        let handle = unsafe { CreateJobObjectW(None, windows::core::PCWSTR::null()) }
            .expect("CreateJobObjectW for test placeholder");
        JobHandle::new(handle)
    }

    /// Test-only: an empty job reached through a handle without `JOB_OBJECT_SET_ATTRIBUTES`, so the
    /// OS refuses `SetInformationJobObject` on it with `ERROR_ACCESS_DENIED`: a real refusal of
    /// `disarm`, which a handle the crate made itself never gives.
    pub(crate) fn create_without_set_access_for_test() -> JobHandle {
        use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_HANDLE_OPTIONS};
        use windows::Win32::System::SystemServices::{JOB_OBJECT_QUERY, JOB_OBJECT_TERMINATE};
        use windows::Win32::System::Threading::GetCurrentProcess;

        let full = JobHandle::create_empty_for_test();
        let mut weak = HANDLE::default();
        full.with_handle(|job| {
            // SAFETY: `job` is live under `full`'s lock; `weak` is an out-parameter.
            unsafe {
                DuplicateHandle(
                    GetCurrentProcess(),
                    job,
                    GetCurrentProcess(),
                    &mut weak,
                    JOB_OBJECT_QUERY | JOB_OBJECT_TERMINATE,
                    false,
                    DUPLICATE_HANDLE_OPTIONS(0),
                )
            }
        })
        .expect("the empty job is live")
        .expect("DuplicateHandle with reduced access");
        JobHandle::new(weak)
    }
}

impl Drop for JobHandle {
    fn drop(&mut self) {
        // If `hard_kill` was not called and `disarm` did not clear the flag,
        // KILL_ON_JOB_CLOSE fires here when we close the handle, tearing down
        // the tree — the drop backstop for `kill_on_drop=true` semantics.
        if let Some(job) = self.take() {
            // SAFETY: job is a valid handle we own.
            unsafe {
                if let Err(e) = CloseHandle(job) {
                    // The close IS the teardown here: with KILL_ON_JOB_CLOSE still set, a
                    // failed close means the tree was never reaped and the handle leaked.
                    // Drop cannot report that, so it must at least be visible.
                    log::warn!("closing the job handle failed ({e}); the tree may still be running");
                }
            }
        }
    }
}

/// Pre-spawn creation flags for a root spawn.
/// `CREATE_SUSPENDED`: child must not execute before it is inside the job.
/// `CREATE_NEW_PROCESS_GROUP`: child leads its own console group so
/// `GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pid)` can target it.
/// Shared by the std path and the raw `CreateProcessW` backend via `windows_contain_setup`.
/// What this word implies about cooperative shutdown is derived by [`mechanism_from_flags`].
pub(crate) fn root_flags() -> u32 {
    CREATE_SUSPENDED.0 | CREATE_NEW_PROCESS_GROUP.0
}

/// Pre-spawn creation flags for a nested (non-root) spawn.
/// Only `CREATE_NEW_PROCESS_GROUP` — no suspension needed for nested spawns.
/// What this word implies about cooperative shutdown is derived by [`mechanism_from_flags`].
pub(crate) fn group_flags() -> u32 {
    CREATE_NEW_PROCESS_GROUP.0
}

/// Which cooperative signal a child spawned with `creation_flags` can be sent, derived from the
/// flag word the spawn actually passed to `CreateProcessW`.
///
/// Three rows:
///
/// - `CREATE_NEW_PROCESS_GROUP` absent → [`GracefulMechanism::None`]. The child sits in the
///   spawner's group, so no console control event can ever be addressed to it individually by
///   any process, and group leadership cannot be changed after creation. This is the one flat
///   negative the flag word settles absolutely.
/// - the group flag set, and none of `DETACHED_PROCESS` / `CREATE_NEW_CONSOLE` /
///   `CREATE_NO_WINDOW` → [`GracefulMechanism::ConsoleGroup`].
/// - the group flag set together with any of those three → [`GracefulMechanism::OtherConsoleGroup`].
///
/// What the results do **not** mean. `ConsoleGroup` says the flags do not *exclude* in-process
/// delivery — it is not a claim the child is reachable. Console membership is not a function of
/// the flag word at all: a GUI-subsystem image never attaches to the spawner's console whatever
/// the flags say, and any child may `FreeConsole`/`AllocConsole`/`AttachConsole` after it starts.
/// An out-of-console group makes `GenerateConsoleCtrlEvent` report success while delivering
/// nothing, which is why the split exists. And `OtherConsoleGroup` is not "unreachable": a child
/// spawned with window suppression owns a *private* console a helper process can attach to, so
/// the claim is about the route from here, never a verdict on the child.
///
/// Any future creation-flag surface must extend this one function rather than deriving a
/// mechanism of its own.
pub(crate) fn mechanism_from_flags(creation_flags: u32) -> crate::graceful::GracefulMechanism {
    use crate::graceful::GracefulMechanism;
    use windows::Win32::System::Threading::{CREATE_NEW_CONSOLE, CREATE_NO_WINDOW, DETACHED_PROCESS};

    if creation_flags & CREATE_NEW_PROCESS_GROUP.0 == 0 {
        return GracefulMechanism::None;
    }
    let out_of_console = DETACHED_PROCESS.0 | CREATE_NEW_CONSOLE.0 | CREATE_NO_WINDOW.0;
    if creation_flags & out_of_console != 0 {
        return GracefulMechanism::OtherConsoleGroup;
    }
    GracefulMechanism::ConsoleGroup
}

/// Clear the inherit flag on the parent's std handles before spawning. Prevents
/// the child from inheriting the test runner's console handles. Best-effort.
pub(crate) fn clear_std_handle_inheritance() {
    for std_handle in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
        // SAFETY: standard Win32 call; handle is not closed.
        unsafe {
            if let Ok(h) = GetStdHandle(std_handle) {
                if !h.is_invalid() {
                    // Clear the INHERIT flag; dwflags=0 means "clear all bits in mask".
                    _ = SetHandleInformation(h, HANDLE_FLAG_INHERIT.0, HANDLE_FLAGS(0));
                }
            }
        }
    }
    #[cfg(test)]
    observe::record_inheritance_cleared();
}

/// Whether THIS process is attached to a console: `Ok(true)` attached, `Ok(false)` genuinely
/// none, `Err` the probe itself failed.
///
/// `GetConsoleProcessList` returns 0 both for "no console" and for an API-level failure, so
/// the two are told apart by the last OS error: a console-less caller gets 0 with
/// `ERROR_INVALID_HANDLE`. Unlike `GetConsoleWindow` this is correct for a *windowless*
/// console (`CREATE_NO_WINDOW`, ConPTY), which can signal fine.
///
/// Used only to CONFIRM a failure that already happened, never to gate one before it. Both
/// orderings race a concurrent `AttachConsole`/`FreeConsole`; a confirmation at worst
/// withholds the typed error, while a guard decides the outcome from state that may already
/// be gone.
pub(crate) fn caller_has_console() -> io::Result<bool> {
    use windows::Win32::Foundation::{SetLastError, ERROR_INVALID_HANDLE, WIN32_ERROR};
    use windows::Win32::System::Console::GetConsoleProcessList;
    #[cfg(test)]
    if fault::take_force_console_probe_error() {
        return Err(io::Error::from_raw_os_error(
            windows::Win32::Foundation::ERROR_INVALID_PARAMETER.0 as i32,
        ));
    }
    let mut list = [0u32; 1];
    // SAFETY: both calls are standard Win32; `list` is a valid writable slice. A buffer
    // smaller than the attached-process count is fine — the return is then the required
    // count, and only "is it zero" is read here. The last error is cleared first: a zero
    // return is only meaningful together with the code THIS call set, and the live caller
    // reaches here right after a `GenerateConsoleCtrlEvent` that itself failed with
    // `ERROR_INVALID_HANDLE` — reading that stale value would let the probe "confirm" an
    // absence it never measured.
    let n = unsafe {
        SetLastError(WIN32_ERROR(0));
        GetConsoleProcessList(&mut list)
    };
    if n != 0 {
        return Ok(true);
    }
    let err = io::Error::last_os_error();
    if err.raw_os_error() == Some(ERROR_INVALID_HANDLE.0 as i32) {
        Ok(false)
    } else {
        Err(err)
    }
}

/// Classify a `GenerateConsoleCtrlEvent` failure. Pure — the Win32 result and the console
/// probe are both parameters — so every arm is unit-testable without hooking the OS calls the
/// live path depends on (the same injection idiom as `treewalk::descendants_with`).
///
/// `err` carries the bare Win32 code (see [`win32_io_error`]).
///
/// `Error::NoConsole` is returned ONLY when the failure code matches AND the probe confirms
/// there is no console. A contradicted probe, a failed probe, or any other failure code keeps
/// the raw `Error::Io`: the typed variant must never assert a cause the process just measured
/// to be false.
pub(crate) fn classify_ctrl_event_failure(pid: u32, err: io::Error, console: io::Result<bool>) -> crate::error::Error {
    use windows::Win32::Foundation::ERROR_INVALID_HANDLE;
    let no_console = ERROR_INVALID_HANDLE.0 as i32;
    if err.raw_os_error() == Some(no_console) && matches!(console, Ok(true)) {
        // warn, not debug: the crate's core mapping (this code <=> no console) was just
        // contradicted. Either another thread attached a console in the confirmation gap, or
        // the mapping does not hold on this host — both deserve to be visible, and neither
        // may be reported as an ordinary Io passthrough without a trace.
        log::warn!(
            "CTRL_BREAK to group {pid} failed with ERROR_INVALID_HANDLE, but a console is \
             attached; surfacing the raw error rather than claiming NoConsole"
        );
        return crate::error::Error::Io(err);
    }
    if err.raw_os_error() == Some(no_console) {
        if let Err(probe) = &console {
            log::warn!("CTRL_BREAK to group {pid}: the console probe failed ({probe}); cannot classify");
            return crate::error::Error::Io(err);
        }
        return crate::error::Error::NoConsole {
            detail: format!(
                "cannot send CTRL_BREAK to process group {pid}: this process has no attached \
                 console. A GUI-subsystem binary, a service, or a detached spawn cannot deliver \
                 console control events — Windows delivers them only within the caller's \
                 console. Attach a console before spawning the tree, or use kill_tree() for a \
                 hard teardown."
            ),
        };
    }
    // The probe cannot change this classification, but if it ALSO failed that is a second,
    // independent OS failure and the arms above log theirs — say so here too rather than
    // dropping it silently.
    if let Err(probe) = &console {
        log::warn!("CTRL_BREAK to group {pid} failed, and the console probe also failed ({probe})");
    }
    crate::error::Error::Io(err)
}

/// What this process's ambient job object says about a child breaking away from it.
///
/// `Unknown` exists for the same reason `identity::Resolved::Unknown` does: cosca must not assert
/// a cause it could not measure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum JobBreakaway {
    NotInJob,
    Permitted,
    /// The job removes new children itself, without them asking — so it does not FORBID
    /// breakaway, and a message saying it does would be wrong about the world.
    SilentBreakaway,
    Forbidden,
    Unknown,
}

/// Read this process's ambient job's breakaway limits.
///
/// Impure, and called only to CLASSIFY a spawn failure that already happened — never to gate one
/// before it. Spawning does not disturb job membership, but membership changes on its own (a
/// process can be assigned to a job at any moment), so a pre-spawn guard would decide the outcome
/// from state that may already be stale, while a post-failure confirmation at worst withholds a
/// typed error. Same impure-probe / pure-classifier split as `caller_has_console` /
/// `classify_ctrl_event_failure`.
///
/// `Permitted` takes precedence over `SilentBreakaway`, because a job setting both does honour
/// the flag.
pub(crate) fn probe_job_breakaway() -> JobBreakaway {
    use windows::Win32::System::JobObjects::{
        IsProcessInJob, JobObjectBasicLimitInformation, QueryInformationJobObject, JOBOBJECT_BASIC_LIMIT_INFORMATION,
        JOB_OBJECT_LIMIT, JOB_OBJECT_LIMIT_BREAKAWAY_OK, JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK,
    };
    use windows::Win32::System::Threading::GetCurrentProcess;

    #[cfg(test)]
    if fault::take_force_job_probe_error() {
        return JobBreakaway::Unknown;
    }

    let mut in_job = windows::core::BOOL(0);
    // SAFETY: standard Win32; `in_job` is a valid out-param, and `None` asks "in ANY job".
    if unsafe { IsProcessInJob(GetCurrentProcess(), None, &mut in_job) }.is_err() {
        return JobBreakaway::Unknown;
    }
    if !in_job.as_bool() {
        return JobBreakaway::NotInJob;
    }

    let mut info = JOBOBJECT_BASIC_LIMIT_INFORMATION::default();
    // SAFETY: standard Win32; `info` is a valid, correctly-sized out-param, and `None` asks about
    // the calling process's own job. The query class returns the BASIC structure even though the
    // matching setter needs the extended one — an asymmetry in the API, not a mistake here.
    let queried = unsafe {
        QueryInformationJobObject(
            None,
            JobObjectBasicLimitInformation,
            std::ptr::addr_of_mut!(info).cast(),
            size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,
            None,
        )
    };
    if queried.is_err() {
        return JobBreakaway::Unknown;
    }
    if info.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK != JOB_OBJECT_LIMIT(0) {
        return JobBreakaway::Permitted;
    }
    if info.LimitFlags & JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK != JOB_OBJECT_LIMIT(0) {
        return JobBreakaway::SilentBreakaway;
    }
    JobBreakaway::Forbidden
}

/// Send `CTRL_BREAK_EVENT` to the process group rooted at `pid`.
/// The child was spawned with `CREATE_NEW_PROCESS_GROUP`, making it the leader;
/// targeting its `pid` reaches the whole group without affecting the parent's console.
/// `CTRL_C` cannot be group-targeted; `CTRL_BREAK` is the only option here.
///
/// **Precondition: the caller holds something that pins `pid`** — the owning `Child`'s process
/// handle, or an identity-verified `ProcessId`. This function takes a raw pid because Win32
/// offers no verify-then-signal primitive, so an unpinned pid could name a recycled process.
///
/// **Requires the CALLER to have a console.** That is the failure this classifies; Windows
/// can also report `ERROR_INVALID_PARAMETER` for a pid that names no process at all, which
/// stays a raw `Error::Io`. The failure code is authoritative; the console probe that follows
/// only *confirms* it, so a console state change in the gap degrades the result to a raw
/// `Error::Io` rather than to a false `NoConsole`.
///
/// **The Win32 return value is evidence in neither direction.** Measured: a target in another
/// console returns success having delivered nothing, and the same class of target returns
/// `ERROR_INVALID_PARAMETER` in another configuration. So the classification above must never
/// be replaced with a return-code check, and success must never be read as delivery.
///
/// **An already-exited target is `Ok`**, because the pinned pid stays allocated and the call
/// succeeds — matching the crate's "already-dead ⇒ `Ok`" contract for the lone signal. A dead
/// group leader is not proof of an empty group either: a signal addressed to one still reaches
/// live members of that group.
///
/// **Two known gaps a caller must plan around.** A target that shares no console with the caller
/// is reported as success and receives nothing; a process attached to the child's *own* console
/// can deliver an event to it, and `kill`/`kill_tree` need no console at all. And every call —
/// including one to an ordinary group that has already drained — leaves a dead entry in the
/// caller's console process list, which persists after the target exits.
///
/// **Absence from the caller's console list is not grounds to refuse.** Membership is readable
/// (`GetConsoleProcessList`), so the first gap's condition is decidable here; the inference is
/// what is missing. Absence is consistent with three states and only one of them is a
/// non-delivery. A contained child is absent at the instant `spawn()` returns — measured 0/10,
/// and 0/10 again for the suspend-then-resume shape a contained root uses — while a signal in
/// that window is delivered and kills it, so refusing would turn a working teardown into an
/// error. An already-exited child is absent too, because a real member's entry is removed on
/// exit, where this function's contract is "already-dead ⇒ `Ok`". The genuinely-elsewhere target
/// is the third, and separating it needs the TARGET's console rather than ours — a broker, not
/// a probe.
pub(crate) fn terminate(pid: u32) -> Result<(), crate::error::Error> {
    use windows::Win32::System::Console::{GenerateConsoleCtrlEvent, CTRL_BREAK_EVENT};
    debug_assert!(
        pid != 0,
        "pid 0 addresses every process attached to the caller's console, including the caller"
    );
    terminate_with(
        pid,
        // SAFETY: standard Win32 call targeting the child's own console group.
        || unsafe { GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pid) },
        caller_has_console,
    )
}

/// [`terminate`] with the OS call `send` and the console probe injected, so a test can make the
/// call fail with the code the OS reports without detaching the test process from its console.
fn terminate_with(
    pid: u32,
    send: impl FnOnce() -> windows::core::Result<()>,
    console: impl FnOnce() -> io::Result<bool>,
) -> Result<(), crate::error::Error> {
    match send() {
        Ok(()) => {
            #[cfg(test)]
            observe::record_ctrl_break(pid);
            Ok(())
        }
        Err(e) => Err(classify_ctrl_event_failure(pid, win32_io_error(e), console())),
    }
}

/// Test-only records of what THIS thread did, with take semantics, mirroring `fault`.
///
/// - `clear_std_handle_inheritance` ran, so a test can prove a refused spawn did not mutate this
///   process first. The real handle flags cannot serve as the observation: the mutation is
///   process-global and permanent, so any earlier contained spawn in the same test binary would
///   already have made it meaningless.
/// - A `CTRL_BREAK` went out: the group `terminate` addressed, once Windows accepted the event.
///   The event lands asynchronously, so a test asserts this before it waits for the target's own
///   evidence, and a call that sent nothing fails that assertion instead of leaving the wait
///   unbounded.
#[cfg(test)]
pub(crate) mod observe {
    use std::cell::{Cell, RefCell};
    thread_local! {
        static INHERITANCE_CLEARED: Cell<bool> = const { Cell::new(false) };
        static CTRL_BREAKS: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
    }
    pub(crate) fn record_inheritance_cleared() {
        INHERITANCE_CLEARED.with(|f| f.set(true));
    }
    pub(crate) fn take_inheritance_cleared() -> bool {
        INHERITANCE_CLEARED.with(|f| f.replace(false))
    }
    pub(crate) fn record_ctrl_break(group: u32) {
        CTRL_BREAKS.with(|b| b.borrow_mut().push(group));
    }
    /// The groups sent a `CTRL_BREAK` on this thread since the last take, in order.
    pub(crate) fn take_ctrl_breaks() -> Vec<u32> {
        CTRL_BREAKS.with(|b| std::mem::take(&mut *b.borrow_mut()))
    }
}

/// Test-only: force the NEXT `caller_has_console` on THIS thread to report a probe failure,
/// so that arm's production is covered — a live `GetConsoleProcessList` cannot be made to
/// fail. Take semantics, mirroring `treewalk::fault`.
#[cfg(test)]
pub(crate) mod fault {
    use std::cell::Cell;
    thread_local! {
        static FORCE_CONSOLE_PROBE_ERROR: Cell<bool> = const { Cell::new(false) };
    }
    pub(crate) fn set_force_console_probe_error(on: bool) {
        FORCE_CONSOLE_PROBE_ERROR.with(|f| f.set(on));
    }
    thread_local! {
        static FORCE_JOB_PROBE_ERROR: Cell<bool> = const { Cell::new(false) };
    }
    /// Force the NEXT `probe_job_breakaway` on THIS thread to report `Unknown`: neither Win32
    /// call it makes can be made to fail on a live system.
    pub(crate) fn set_force_job_probe_error(on: bool) {
        FORCE_JOB_PROBE_ERROR.with(|f| f.set(on));
    }
    pub(crate) fn take_force_job_probe_error() -> bool {
        FORCE_JOB_PROBE_ERROR.with(|f| f.replace(false))
    }
    pub(crate) fn take_force_console_probe_error() -> bool {
        FORCE_CONSOLE_PROBE_ERROR.with(|f| f.replace(false))
    }
    pub(crate) fn armed() -> bool {
        FORCE_CONSOLE_PROBE_ERROR.with(|f| f.get())
    }

    /// The Win32 call `resume_if_owned` makes at each step, for [`force_next`].
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Step {
        QueryOpen,
        Owner,
        ResumeOpen,
        Resume,
        /// The read of a thread's creation time, in the search for a frozen child's initial thread.
        CreationTime,
        /// The assignment of a Strongest root's job.
        Assign,
    }

    thread_local! {
        static INJECTED: Cell<Option<(u32, Option<u32>)>> = const { Cell::new(None) };
        static INJECTED_VISIT: Cell<Option<Option<super::Visit>>> = const { Cell::new(None) };
        static FORCED: Cell<Option<(Step, u32, Option<u32>)>> = const { Cell::new(None) };
        static EQUAL_CREATION_TIMES: Cell<bool> = const { Cell::new(false) };
    }
    /// Make `resume_initial_threads` on THIS thread walk one extra snapshot entry for thread
    /// `tid`, owned by `owner` (`None`: the CHILD's pid, which is what a stale id looks like).
    /// Reset on drop, which also clears the recorded visit and any forced failure.
    pub(crate) fn inject_snapshot_tid(tid: u32, owner: Option<u32>) -> Injected {
        INJECTED.with(|f| {
            debug_assert!(f.get().is_none(), "a snapshot tid is already injected");
            f.set(Some((tid, owner)));
        });
        INJECTED_VISIT.with(|f| f.set(None));
        Injected(())
    }
    /// The injected entry's `(tid, owner)`.
    pub(crate) fn injected_entry() -> Option<(u32, Option<u32>)> {
        INJECTED.with(|f| f.get())
    }
    /// Record what the walk did with the injected entry (`None`: the owner filter dropped it).
    pub(crate) fn record_injected_visit(visit: Option<super::Visit>) {
        INJECTED_VISIT.with(|f| f.set(Some(visit)));
    }
    /// What the walk did with the injected entry. The outer `None` means it was never walked.
    pub(crate) fn take_injected_visit() -> Option<Option<super::Visit>> {
        INJECTED_VISIT.with(|f| f.take())
    }
    /// Make the NEXT `step` call on THIS thread fail with Win32 error `code`. Reset on drop of the
    /// guard. Neither an owner of 0 nor a failed `ResumeThread` can be produced on a live system.
    pub(crate) fn force_next(step: Step, code: u32) -> Forced {
        arm(step, code, None)
    }
    /// [`force_next`], but only for the call that handles thread `tid`; a call for another thread
    /// does not consume it.
    pub(crate) fn force_next_for_thread(step: Step, code: u32, tid: u32) -> Forced {
        arm(step, code, Some(tid))
    }
    fn arm(step: Step, code: u32, tid: Option<u32>) -> Forced {
        FORCED.with(|f| {
            debug_assert!(f.get().is_none(), "a failure is already forced");
            f.set(Some((step, code, tid)));
        });
        Forced(())
    }
    /// Whether a forced failure is still armed: the call it was armed for never happened.
    pub(crate) fn forced_is_armed() -> bool {
        FORCED.with(|f| f.get().is_some())
    }
    /// Consume a forced failure for `step` (on thread `tid`, where the call has one), if one is
    /// armed for it.
    pub(crate) fn take_forced(step: Step, tid: Option<u32>) -> Option<u32> {
        FORCED.with(|f| match f.get() {
            Some((armed, code, only)) if armed == step && (only.is_none() || only == tid) => {
                f.set(None);
                Some(code)
            }
            _ => None,
        })
    }
    /// Make every creation time read on THIS thread answer the same value, as a coarse clock would,
    /// until the guard drops. No live system can be made to tie.
    pub(crate) fn equal_creation_times() -> EqualTimes {
        EQUAL_CREATION_TIMES.with(|f| f.set(true));
        EqualTimes(())
    }
    pub(crate) fn creation_times_are_equal() -> bool {
        EQUAL_CREATION_TIMES.with(|f| f.get())
    }
    #[must_use = "dropping this immediately restores the real clock"]
    pub(crate) struct EqualTimes(());
    impl Drop for EqualTimes {
        fn drop(&mut self) {
            EQUAL_CREATION_TIMES.with(|f| f.set(false));
        }
    }
    #[must_use = "dropping this immediately removes the injected entry"]
    pub(crate) struct Injected(());
    impl Drop for Injected {
        fn drop(&mut self) {
            INJECTED.with(|f| f.set(None));
            INJECTED_VISIT.with(|f| f.set(None));
        }
    }
    #[must_use = "dropping this immediately disarms the forced failure"]
    pub(crate) struct Forced(());
    impl Drop for Forced {
        fn drop(&mut self) {
            FORCED.with(|f| f.set(None));
        }
    }
}

/// Create a `KILL_ON_JOB_CLOSE` job and assign the process at `proc_handle` to it.
///
/// `pub(crate)`: also the sole constructor behind the public [`crate::containment::job::Job`]
/// primitive — reused verbatim rather than duplicated, so `Command::contain()` and `Job::assign`
/// share exactly one implementation.
pub(crate) fn assign_to_kill_on_close_job(proc_handle: std::os::windows::io::RawHandle) -> io::Result<JobHandle> {
    // A Windows `RawHandle` is a `*mut c_void`.
    let raw_handle = HANDLE(proc_handle.cast());
    // SAFETY: a standard Win32 call; its handle is closed on every error path below.
    let job = owned_job(unsafe { CreateJobObjectW(None, windows::core::PCWSTR::null()) })?;
    set_kill_on_close_or_close(job)?;
    assign_or_close(job, raw_handle)?;
    Ok(JobHandle::new(job))
}

/// The job `CreateJobObjectW` made, or its failure with the plain Win32 code.
fn owned_job(created: windows::core::Result<HANDLE>) -> io::Result<HANDLE> {
    created.map_err(win32_io_error)
}

/// Set `KILL_ON_JOB_CLOSE` on `job`. On failure `job` is closed and the error has the plain Win32
/// code.
fn set_kill_on_close_or_close(job: HANDLE) -> io::Result<()> {
    let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
    info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
    // SAFETY: `info` is a live local of exactly the size passed.
    let set = unsafe {
        SetInformationJobObject(
            job,
            JobObjectExtendedLimitInformation,
            std::ptr::addr_of!(info).cast(),
            size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
        )
    };
    if let Err(e) = set {
        // SAFETY: the caller hands `job` over; nothing else closes it.
        _ = unsafe { CloseHandle(job) };
        return Err(win32_io_error(e));
    }
    Ok(())
}

/// Assign `process` to `job`. On failure `job` is closed and the error has the plain Win32 code.
fn assign_or_close(job: HANDLE, process: HANDLE) -> io::Result<()> {
    // SAFETY: a standard Win32 call on handles the caller keeps open across it.
    if let Err(e) = unsafe { AssignProcessToJobObject(job, process) } {
        // SAFETY: the caller hands `job` over; nothing else closes it.
        _ = unsafe { CloseHandle(job) };
        return Err(win32_io_error(e));
    }
    Ok(())
}

/// [`assign_to_kill_on_close_job`] as `attach` takes it: the job is assigned and the child is NOT
/// resumed.
pub(crate) fn assign_held(proc_handle: std::os::windows::io::RawHandle) -> io::Result<JobHandle> {
    #[cfg(test)]
    forced(fault::Step::Assign, None).map_err(win32_io_error)?;
    assign_to_kill_on_close_job(proc_handle)
}

/// Read the job's LIVE member pids via `QueryInformationJobObject(JobObjectBasicProcessIdList)`
/// — the authoritative, always-fresh source `wait_drained` re-consults every round, independent
/// of any completion-port message. Grows the buffer and retries (no bound on retries: a job
/// that keeps growing needs an ever-larger buffer, but capping this would silently under-report
/// live membership rather than fail loudly).
pub(crate) fn query_job_pid_list(job: HANDLE) -> io::Result<Vec<u32>> {
    let mut capacity: usize = 64;
    loop {
        let buf_len = size_of::<JOBOBJECT_BASIC_PROCESS_ID_LIST>() + capacity.saturating_sub(1) * size_of::<usize>();
        // Backed by `Vec<usize>`, not `Vec<u8>`: `JOBOBJECT_BASIC_PROCESS_ID_LIST` is 8-aligned
        // (it holds `usize` fields), but a `Vec<u8>`'s allocation is only ever requested at
        // alignment 1. Forming a `&JOBOBJECT_BASIC_PROCESS_ID_LIST` from a `Vec<u8>` buffer is
        // undefined behaviour regardless of what the allocator happens to return in practice —
        // the compiler is entitled to assume the reference's target is properly aligned. A
        // `Vec<usize>` buffer is naturally aligned for this header, and is read through raw
        // pointers below rather than a reference, so no alignment assumption is ever load-bearing.
        let mut buf: Vec<usize> = vec![0usize; buf_len.div_ceil(size_of::<usize>())];
        let mut returned = 0u32;
        let header_ptr = buf.as_mut_ptr().cast::<JOBOBJECT_BASIC_PROCESS_ID_LIST>();
        // SAFETY: `buf` is at least `buf_len` bytes (rounded up to whole `usize`s),
        // zero-initialized, matching the trailing `ProcessIdList` array's declared capacity; the
        // call writes at most `buf_len` bytes.
        let result = unsafe {
            QueryInformationJobObject(
                Some(job),
                JobObjectBasicProcessIdList,
                header_ptr.cast(),
                buf_len as u32,
                Some(&mut returned),
            )
        };
        // The fixed header (`NumberOfAssignedProcesses`/`NumberOfProcessIdsInList`) is always
        // written even when the call fails with a too-small buffer. Read both fields via
        // `addr_of!`/`read_unaligned` on the raw pointer rather than materialising a
        // `&JOBOBJECT_BASIC_PROCESS_ID_LIST` reference, so this call never depends on forming a
        // reference into a buffer the kernel writes out-of-band.
        // SAFETY: `header_ptr` is valid for reads of `size_of::<JOBOBJECT_BASIC_PROCESS_ID_LIST>()`
        // bytes (`buf_len` is at least that size by construction) and initialized (zeroed above,
        // then possibly partially overwritten by the call).
        let assigned = unsafe { std::ptr::addr_of!((*header_ptr).NumberOfAssignedProcesses).read_unaligned() } as usize;
        if result.is_err() {
            if assigned > capacity {
                capacity = assigned;
                continue;
            }
            return Err(io::Error::last_os_error());
        }
        // SAFETY: same as above.
        let n = unsafe { std::ptr::addr_of!((*header_ptr).NumberOfProcessIdsInList).read_unaligned() } as usize;
        debug_assert!(
            n <= capacity,
            "kernel reported more pids than the queried buffer could hold"
        );
        // SAFETY: `ProcessIdList` is the header's trailing flexible-array member; `buf` was sized
        // for `capacity` entries starting right after the two `u32` counters, and
        // `n.min(capacity) <= capacity`, so every read below is in-bounds and initialized.
        let list_ptr = unsafe { std::ptr::addr_of!((*header_ptr).ProcessIdList).cast::<usize>() };
        let mut pids = Vec::with_capacity(n.min(capacity));
        for i in 0..n.min(capacity) {
            // SAFETY: see above.
            let raw = unsafe { list_ptr.add(i).read_unaligned() };
            pids.push(raw as u32);
        }
        return Ok(pids);
    }
}

/// The largest handle count a single `WaitForMultipleObjects` call accepts (`MAXIMUM_WAIT_OBJECTS`).
const MAXIMUM_WAIT_OBJECTS: usize = 64;

impl JobHandle {
    /// Block until every process in this job has EXITED (not reaped), or until `deadline`.
    ///
    /// Deliberately does not associate an I/O completion port with the job at all: every
    /// ordinary job-lifecycle completion-port message (`JOB_OBJECT_MSG_EXIT_PROCESS`,
    /// `JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO`, ...) is documented by Microsoft as **not guaranteed
    /// to be delivered** — only `JobObjectNotificationLimitInformation`-class resource-limit
    /// messages carry a delivery guarantee, a class unrelated to process lifecycle. Trusting a
    /// port for this call's own correctness would make an unbounded `wait_tree()` capable of a
    /// caller-invisible infinite hang on a single dropped packet — and with the port never read,
    /// associating one anyway would only cost unbounded kernel nonpaged-pool growth (one queued
    /// packet per job lifecycle event, for the job handle's whole lifetime) for nothing.
    ///
    /// Instead, each round: (1) re-enumerate the job's LIVE members via
    /// `QueryInformationJobObject(JobObjectBasicProcessIdList)` — the authoritative, always-fresh
    /// source of truth, independent of any notification; (2) if empty, the tree has drained; (3)
    /// otherwise open real `SYNCHRONIZE` handles to up to `MAXIMUM_WAIT_OBJECTS - 1` of those
    /// pids and block on `WaitForMultipleObjects(bWaitAll = FALSE)`. A process handle becoming
    /// signaled on exit is an unconditional, always-honored OS guarantee — unlike a job message
    /// — so as long as this round's tree is non-empty, at least one tracked handle WILL
    /// eventually signal, forcing a fresh re-enumeration next round. While the job handle is
    /// still open, this can never falsely report `AllMembersExited` (that verdict is only ever
    /// reached via a live re-count of zero); it can only be slow to *notice* full drain when
    /// concurrently-live membership exceeds `MAXIMUM_WAIT_OBJECTS - 1` in a single round (this
    /// round's un-tracked excess is picked up on the NEXT re-enumeration, once a tracked handle
    /// signals). If the job handle has ALREADY been consumed by the time this call runs, there
    /// is nothing left to re-enumerate at all — see the early return below, which reports
    /// [`Error::Unassessable`](crate::error::Error::Unassessable) rather than guess.
    ///
    /// `deadline`: `None` is no deadline (see [`crate::wait::remaining`]). No interval is chosen
    /// anywhere in this path: every round blocks in one `WaitForMultipleObjects` call for exactly
    /// the caller's own remaining time. An already-elapsed (or `Duration::ZERO`) deadline still
    /// gets one real re-enumeration and, if any member is still live, one real non-blocking
    /// `WaitForMultipleObjects` poll before a deadline-based verdict is returned — a stale bound
    /// only ever forecloses looping back for ANOTHER round, never the current one's own
    /// observation. A drained tree is reported `AllMembersExited` regardless of how late the
    /// caller arrived to look.
    ///
    /// `cancel`, when given, is appended to every round's wait set (one fewer live member
    /// tracked per round) so a live `WaitForMultipleObjects` releases the instant it is
    /// signaled rather than only at the next re-enumeration boundary — the async wrapper's
    /// drop-cancellation primitive (mirrors `wait_process_or_cancel`'s cancel event). A
    /// cancellation reports `MembersRemain` (the tree's drain state is simply unknown at that
    /// point, same as a timeout), never an error. Unlike the deadline, cancellation IS checked
    /// before that first re-enumeration too: it is a genuine "stop looking" instruction, not a
    /// stale bound on how long to keep looking, so a caller who cancels before this call ever
    /// enumerates the job once still gets a prompt `MembersRemain` rather than being forced
    /// through one more round first.
    pub(crate) fn wait_drained(
        &self,
        deadline: Option<std::time::Instant>,
        cancel: Option<HANDLE>,
    ) -> Result<crate::containment::TreeDrain, crate::error::Error> {
        #[cfg(feature = "tokio")]
        crate::bounded::assert_may_block("waiting for a job to drain");
        // Duplicate under the lock, then wait on the duplicate. The wait can block for the
        // whole deadline, and holding the lock for that long would stall `hard_kill`/`Drop`
        // (and, with an unbounded deadline, forever). The duplicate is an independent
        // reference to the same job, so closing the original elsewhere cannot invalidate it.
        let Some(dup) = self.with_handle(duplicate_job).transpose()? else {
            // The job was already consumed — `hard_kill()` or `Drop` already ran, nulling `raw`
            // and closing the underlying handle. See `consumed_job_handle_error`'s own doc for
            // why that is reported as `Unassessable` rather than a guessed `AllMembersExited`.
            return Err(consumed_job_handle_error());
        };
        let result = wait_drained_raw(dup, deadline, cancel);
        // SAFETY: `dup` is ours alone and no longer in use.
        unsafe {
            _ = CloseHandle(dup);
        }
        result
    }
}

/// The [`Error::Unassessable`](crate::error::Error::Unassessable) reported when a drain check
/// finds the job handle already closed (`kill_tree()`/`hard_kill()`, or the owning `Child`/`Job`
/// was dropped): `TerminateJobObject`/`CloseHandle` are not documented as synchronous with member
/// process teardown, so once the handle is gone there is no way left to ask whether every member
/// has actually finished exiting — reporting `AllMembersExited` here would be a guess, not a
/// live-checked verdict. Shared verbatim by `JobHandle::wait_drained`'s own early return, its
/// tokio twin `job_wait_tree_drained`, and the public [`crate::containment::job::Job`] wrapper.
pub(crate) fn consumed_job_handle_error() -> crate::error::Error {
    crate::error::Error::Unassessable {
        detail: "the job handle was already closed (kill_tree()/hard_kill(), or the owning \
                 Child/Job was dropped) before this drain check ran; whether every member has \
                 actually finished exiting can no longer be observed"
            .into(),
        source: None,
    }
}

/// Duplicate a job handle. One implementation for all three duplicate-then-wait sites (the
/// sync wait, the async wait, and `Job::wait_tree`); it lives here, next to `JobHandle`,
/// rather than in `job.rs`, because the public wrapper depends on this module and not the
/// other way round.
///
/// Call it as the closure passed to [`JobHandle::with_handle`], never on a handle returned
/// out of one: the point is that the lock is still held while `DuplicateHandle` reads it.
/// Returning the handle first and duplicating after is the same load-then-use gap with extra
/// steps — and reads as correct, which is why it is called out here.
pub(crate) fn duplicate_job(handle: HANDLE) -> Result<HANDLE, crate::error::Error> {
    use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS};
    use windows::Win32::System::Threading::GetCurrentProcess;

    let mut dup = HANDLE::default();
    // SAFETY: `handle` is live for the duration of this call (borrowed from `self.0`, which
    // outlives this function call); `dup` is an out-parameter DuplicateHandle initializes.
    unsafe {
        DuplicateHandle(
            GetCurrentProcess(),
            handle,
            GetCurrentProcess(),
            &mut dup,
            0,
            false,
            DUPLICATE_SAME_ACCESS,
        )
    }
    .map_err(win32_io_error)?;
    Ok(dup)
}

/// Whether the process `OpenProcess` returned as `opened` is a member of `job`: its handle to wait
/// on if so, `None` if it is not one, and the failure (with the plain Win32 code) if membership
/// could not be established. The handle is closed unless it is returned.
fn member_to_watch(opened: windows::core::Result<HANDLE>, job: HANDLE) -> io::Result<Option<HANDLE>> {
    match opened {
        // A pid enumerated a moment ago can have exited and had its number reused by the time it
        // is opened, so membership is re-confirmed against the job rather than assumed. Waiting
        // on a bystander would either hang the drain (it outlives the tree) or, if it exits
        // first, report the tree drained while members run.
        Ok(h) => {
            use windows::Win32::System::JobObjects::IsProcessInJob;
            let mut in_job = windows::core::BOOL(0);
            // SAFETY: both handles are valid for the duration of the call.
            let confirmed = unsafe { IsProcessInJob(h, Some(job), &mut in_job) };
            match confirmed {
                // A member: wait on it.
                Ok(()) if in_job.as_bool() => Ok(Some(h)),
                // Openable but not in this job: the pid was recycled between the enumeration and
                // the open. Filtering it out is the point.
                Ok(()) => {
                    // SAFETY: opened by the caller and not stored anywhere.
                    _ = unsafe { CloseHandle(h) };
                    Ok(None)
                }
                // The query itself failed, so membership is unknown. Recorded like any other
                // actionable failure rather than silently dropped: if it holds for every member
                // it would otherwise be invisible.
                Err(e) => {
                    // SAFETY: opened by the caller and not stored anywhere.
                    _ = unsafe { CloseHandle(h) };
                    Err(win32_io_error(e))
                }
            }
        }
        // ERROR_INVALID_PARAMETER: the pid no longer names a process: it exited in the race
        // between the enumeration and the open. That is real progress (this round's tree is
        // shrinking), not a failure: loop back to re-enumerate rather than treating it as denied.
        Err(e) if e.code() == windows::Win32::Foundation::ERROR_INVALID_PARAMETER.to_hresult() => Ok(None),
        Err(e) => Err(win32_io_error(e)),
    }
}

/// The Toolhelp thread snapshot `CreateToolhelp32Snapshot` made, or its failure with the plain
/// Win32 code.
fn thread_snapshot(created: windows::core::Result<HANDLE>) -> io::Result<HANDLE> {
    created.map_err(win32_io_error)
}

/// Every entry of the thread snapshot `snap`, which is closed on every path. A failure of the
/// snapshot API has the plain Win32 code; the end of the walk is not one.
fn thread_entries_closing(
    snap: HANDLE,
) -> io::Result<Vec<windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32>> {
    use windows::Win32::Foundation::ERROR_NO_MORE_FILES;
    use windows::Win32::System::Diagnostics::ToolHelp::{Thread32First, Thread32Next, THREADENTRY32};

    // Thread32First/Next signal end-of-enumeration with ERROR_NO_MORE_FILES.
    let end_of_walk = windows::core::HRESULT::from_win32(ERROR_NO_MORE_FILES.0);
    let mut entry = THREADENTRY32 {
        dwSize: size_of::<THREADENTRY32>() as u32,
        ..Default::default()
    };
    let mut entries = Vec::new();
    // SAFETY: `snap` is a handle the caller hands over; `entry` has its `dwSize` set.
    let mut step = unsafe { Thread32First(snap, &mut entry) };
    let walked = loop {
        match step {
            Ok(()) => {}
            Err(e) if e.code() == end_of_walk => break Ok(entries),
            // A snapshot-API fault, not normal end-of-iteration.
            Err(e) => break Err(win32_io_error(e)),
        }
        entries.push(entry);
        // SAFETY: as for `Thread32First`.
        step = unsafe { Thread32Next(snap, &mut entry) };
    };
    // SAFETY: handed over by the caller; closed once, here.
    _ = unsafe { CloseHandle(snap) };
    walked
}

/// The loop body of [`JobHandle::wait_drained`], taking an already-resolved raw handle rather
/// than borrowing `&JobHandle`.
///
/// Every caller now hands in an owned duplicate taken under the lock, not the live handle, so
/// this can run for an unbounded deadline without holding off `hard_kill`/`Drop` and without
/// the handle being closed underneath it.
pub(crate) fn wait_drained_raw(
    job: HANDLE,
    deadline: Option<std::time::Instant>,
    cancel: Option<HANDLE>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
    use crate::containment::TreeDrain;
    use crate::error::Error;

    #[cfg(feature = "tokio")]
    crate::bounded::assert_may_block("waiting for a job to drain");
    let budget = MAXIMUM_WAIT_OBJECTS - 1 - if cancel.is_some() { 1 } else { 0 };
    loop {
        // Cancellation is checked BEFORE any work this round, including the very first — a
        // deliberate asymmetry with the deadline check below. Cancellation is a genuine "stop
        // looking" instruction (the caller's future was dropped; the tree's drain state is no
        // longer anyone's to observe), so it is honored even before we have ever enumerated the
        // job once. A deadline, in contrast, is a stale BOUND on how long to keep looking, not
        // an instruction to skip looking — see below.
        if let Some(c) = cancel {
            // SAFETY: `cancel` is a valid handle for the duration of this call (caller-owned).
            let cancel_state = unsafe { WaitForSingleObject(c, 0) };
            if cancel_state == WAIT_OBJECT_0 {
                return Ok(TreeDrain::MembersRemain);
            }
        }

        // Re-enumerate BEFORE consulting the deadline for a return. A `Duration::ZERO` (or
        // already-elapsed) deadline must still observe the tree's ACTUAL current state on the
        // one round it gets, not conclude `MembersRemain` purely because it arrived too late to
        // look — a ZERO probe on an already-drained tree must report `AllMembersExited`, the
        // same verdict an unbounded wait would find. This mirrors `Kqueue::wait` on the macOS
        // side, which takes one look at an elapsed deadline: the real observation always happens
        // first; an elapsed deadline only forecloses looping back for ANOTHER round afterward
        // (see the `handles.is_empty()` branch below, and the `ms` computation for the bounded
        // wait itself).
        let pids = query_job_pid_list(job).map_err(Error::Io)?;
        if pids.is_empty() {
            return Ok(TreeDrain::AllMembersExited);
        }

        let mut handles: Vec<HANDLE> = Vec::new();
        let mut denied: Option<io::Error> = None;
        for pid in pids.iter().take(budget) {
            // SAFETY: standard Win32 call; the handle is closed by `member_to_watch` unless it is
            // returned. `PROCESS_QUERY_LIMITED_INFORMATION` is required by `IsProcessInJob` there
            // and is NOT implied by `PROCESS_SYNCHRONIZE`; without it every membership check fails
            // ACCESS_DENIED, `handles` stays empty forever, and this loop spins instead of
            // ever reaching `WaitForMultipleObjects`. (`job_contains_pid` opens for the same
            // reason.) `LIMITED` rather than full query: it is the least right that works and
            // is grantable across integrity levels.
            let opened = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, *pid) };
            match member_to_watch(opened, job) {
                Ok(Some(h)) => handles.push(h),
                Ok(None) => {}
                Err(e) => denied = Some(e),
            }
        }

        // Computed once per round and reused below for both the empty-handles decision and the
        // bounded-wait timeout, so the two agree on what "the deadline" means for this round.
        let remaining = crate::wait::remaining(deadline);

        if handles.is_empty() {
            if let Some(e) = denied {
                // A persistent, actionable open failure (not a benign exit-race): looping
                // back here without ever holding a real handle to block on would busy-spin.
                log::warn!("wait_tree: could not open any live job member to watch for its exit ({e})");
                return Err(Error::Unassessable {
                    detail: "could not open a handle to any live member of the contained tree \
                                 to observe its exit"
                        .into(),
                    source: Some(e),
                });
            }
            // Every candidate in this round's batch had already exited by the time we tried
            // to open it — real progress, but this round's `pids` was non-empty (so
            // `AllMembersExited` isn't supported by what was actually observed) and looping
            // straight back to `query_job_pid_list` is itself another round, which a bounded
            // wait must not be allowed to take once its deadline has already elapsed (the
            // busy-spin/cancellation-starvation hazard this whole restructuring exists to
            // close). An elapsed deadline concludes `MembersRemain` here instead of continuing.
            if remaining == Some(std::time::Duration::ZERO) {
                return Ok(TreeDrain::MembersRemain);
            }
            continue;
        }
        if let Some(e) = &denied {
            // Some sibling in this round was still openable, so the round proceeds — but an
            // actionable `OpenProcess` failure on a live member (as opposed to the benign
            // exit-race above) is otherwise invisible for every round in which that holds,
            // which can be every round for the tree's whole lifetime. Every other known
            // failure in this function gets a visible disposition; this one should too, even
            // though it isn't (yet) fatal to this round's wait.
            log::debug!(
                "wait_tree: could not open one live job member to watch for its exit, but \
                 other members are still trackable this round: {e}"
            );
        }

        // The cancel handle (if any) is appended AFTER the real member handles, never
        // closed here (caller-owned) — only `handles` (the freshly opened member handles)
        // are closed below.
        let mut wait_set = handles.clone();
        if let Some(c) = cancel {
            wait_set.push(c);
        }

        // An elapsed deadline arms `ms == 0`, a real non-blocking poll of the handles just
        // opened, so a ZERO deadline still gets one look before `MembersRemain`.
        // A WAIT_TIMEOUT is never trusted: recheck the real deadline each round (see win32_timeout_ms).
        // SAFETY: every handle in `handles` was just opened above and stays open for the
        // duration of this call; `cancel`, if present, is kept alive by its caller for the
        // same duration.
        let waited = crate::wait::wait_until(deadline, |ms| unsafe { WaitForMultipleObjects(&wait_set, false, ms) });
        let wait_failed = (waited == WAIT_FAILED).then(io::Error::last_os_error);
        for h in &handles {
            // SAFETY: each handle was opened above; closing after the wait releases it
            // regardless of which handle (if any) was signaled.
            unsafe {
                _ = CloseHandle(*h);
            }
        }

        if waited == WAIT_TIMEOUT {
            // `wait_until` returns WAIT_TIMEOUT only once the real deadline has passed.
            return Ok(TreeDrain::MembersRemain);
        }
        if let Some(e) = wait_failed {
            return Err(Error::Io(e));
        }
        let idx = waited.0.wrapping_sub(WAIT_OBJECT_0.0) as usize;
        debug_assert!(
            idx < wait_set.len(),
            "unexpected WaitForMultipleObjects verdict: {waited:?}"
        );
        if idx >= wait_set.len() {
            // Same anomaly the debug_assert above catches in debug builds — surfaced here too
            // so a release build does not silently fall through to "treat as a member exit and
            // re-enumerate" without any trace of the OS having returned an unexpected verdict.
            log::warn!(
                "wait_tree: unexpected WaitForMultipleObjects verdict {waited:?} (index {idx} \
                 outside the {} handles waited on) - re-enumerating regardless",
                wait_set.len()
            );
        }
        if cancel.is_some() && idx == handles.len() {
            // The cancel handle was signaled — the caller's future was dropped. The
            // tree's drain state is genuinely unknown at this instant; report it exactly
            // like a timeout rather than inventing a verdict.
            return Ok(TreeDrain::MembersRemain);
        }
        // A tracked member exited — loop back and re-enumerate the authoritative live set.
    }
}

/// What `resume_if_owned` did with one thread id.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Visit {
    Resumed,
    /// The opened thread belongs to `owner`, not to the child: the id was reused.
    Foreign {
        owner: u32,
    },
    /// No thread has this id any more (`ERROR_INVALID_PARAMETER`).
    Gone,
    /// The query-only open was denied. The child's own threads are openable by its creator, so
    /// the id belongs to someone else.
    Denied,
    /// A call failed on a thread that is the child's; recorded in `last_err`.
    Failed,
}

/// What a resume asks of the suspend count it answers.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum SuspendCount {
    /// Any count: the ordinary `contain()` spawn resumes whatever the snapshot lists and accepts a
    /// thread something else already ran.
    #[default]
    Any,
    /// A frozen child's release: resumes the child's INITIAL thread only, and only if its previous
    /// count was exactly 1. An initial thread that ran, or that something else suspended again,
    /// means the child is not as its creator left it. Every other thread (one an EDR agent or a
    /// debugger started) is opened query-only, to read its creation time, and never for
    /// suspend/resume: the creator suspended only the initial thread, so a resume of any other would
    /// take away a suspension that is someone else's. Other threads are never resumed and keep
    /// their count. The initial thread is the one created first, so the release fails, resuming
    /// nothing, if the creation time of any thread of the child cannot be read or the earliest two
    /// are equal. A thread that is gone, or that the creator cannot open, is skipped.
    ExactlyOne,
}

/// The state of one walk over the snapshot.
#[derive(Default)]
struct Walk {
    expected: SuspendCount,
    resumed: u32,
    /// The FIRST failure: it is the root cause, and later ones are logged as they happen.
    last_err: Option<io::Error>,
    /// Reason for the latest stale skip, for the none-resumed error.
    last_skip: Option<String>,
}

impl Walk {
    fn skip(&mut self, reason: String) {
        log::debug!("resume_initial_threads: {reason}; skipped");
        self.last_skip = Some(reason);
    }

    /// Record that the initial thread of `process_pid` cannot be told from the threads `first` and
    /// `second`.
    fn fail_unidentified(&mut self, process_pid: u32, first: u32, second: u32) {
        let msg = format!(
            "the initial thread of pid {process_pid} cannot be identified: threads {first} and {second} have the same creation time"
        );
        log::warn!("resume_initial_threads: {msg}");
        self.last_err.get_or_insert_with(|| io::Error::other(msg));
    }

    /// Record a failure that is cosca's own finding about a thread. No OS call failed, so the error
    /// has no OS code.
    fn fail(&mut self, call: &str, tid: u32, process_pid: u32, cause: impl std::fmt::Display) -> Visit {
        let msg = format!("{call} failed for thread {tid} of pid {process_pid}: {cause}");
        log::warn!("resume_initial_threads: {msg}");
        self.last_err.get_or_insert_with(|| io::Error::other(msg));
        Visit::Failed
    }

    /// Record the failure of the Win32 call `call`, keeping its code as the error's source.
    fn fail_win32(&mut self, call: &str, tid: u32, process_pid: u32, cause: windows::core::Error) -> Visit {
        let context = format!("{call} failed for thread {tid} of pid {process_pid}");
        let err = io_context(context, win32_io_error(cause));
        log::warn!("resume_initial_threads: {err}");
        self.last_err.get_or_insert(err);
        Visit::Failed
    }
}

/// A thread handle, closed on drop.
struct ThreadHandle(HANDLE);

impl Drop for ThreadHandle {
    fn drop(&mut self) {
        // SAFETY: the handle is owned and closed exactly once.
        unsafe { _ = CloseHandle(self.0) };
    }
}

/// Fail with the Win32 error a test armed for `step`, if any.
#[cfg(test)]
fn forced(step: fault::Step, tid: Option<u32>) -> windows::core::Result<()> {
    match fault::take_forced(step, tid) {
        Some(code) => Err(windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(
            code,
        ))),
        None => Ok(()),
    }
}

fn open_query(tid: u32) -> windows::core::Result<ThreadHandle> {
    #[cfg(test)]
    forced(fault::Step::QueryOpen, Some(tid))?;
    // SAFETY: plain Win32 call; the handle is owned by the returned guard.
    unsafe { OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, tid) }.map(ThreadHandle)
}

fn open_for_resume(tid: u32) -> windows::core::Result<ThreadHandle> {
    #[cfg(test)]
    forced(fault::Step::ResumeOpen, Some(tid))?;
    // SAFETY: plain Win32 call; the handle is owned by the returned guard.
    unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_QUERY_LIMITED_INFORMATION, false, tid) }.map(ThreadHandle)
}

fn owner_of(thread: &ThreadHandle) -> windows::core::Result<u32> {
    #[cfg(test)]
    forced(fault::Step::Owner, None)?;
    // SAFETY: `thread` is a live handle with THREAD_QUERY_LIMITED_INFORMATION.
    match unsafe { GetProcessIdOfThread(thread.0) } {
        0 => Err(windows::core::Error::from_thread()),
        pid => Ok(pid),
    }
}

/// `ResumeThread`, answering the suspend count the thread had before: a frozen child's initial
/// thread has exactly 1.
fn resume_thread(thread: &ThreadHandle) -> windows::core::Result<u32> {
    #[cfg(test)]
    forced(fault::Step::Resume, None)?;
    // ResumeThread returns the previous suspend count, or u32::MAX on failure.
    // SAFETY: `thread` is a live handle with THREAD_SUSPEND_RESUME.
    match unsafe { ResumeThread(thread.0) } {
        u32::MAX => Err(windows::core::Error::from_thread()),
        previous => Ok(previous),
    }
}

/// Walk one snapshot entry; `None` if the snapshot lists it under another pid. Ownership is then
/// re-checked on the opened handle by [`resume_if_owned`].
fn visit_thread_entry(
    entry: &windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32,
    process_pid: u32,
    walk: &mut Walk,
) -> Option<Visit> {
    (entry.th32OwnerProcessID == process_pid).then(|| resume_if_owned(entry.th32ThreadID, process_pid, walk))
}

/// Resume thread `tid` only if it provably belongs to `process_pid`.
///
/// The Toolhelp snapshot is stale by the time the thread is opened: an id can be released and
/// reused by another process, or released and not reused. So:
/// 1. Open with query-only rights and KEEP the handle: it pins the thread, so the id cannot be
///    reused while it is held. Read the owner through it. A thread's owner never changes.
/// 2. Only for the child's own thread, open with suspend/resume rights (the pin guarantees it
///    is the same thread), re-check the owner on that handle, and resume.
///
/// A stale id (reused, gone, or not openable by the child's creator) means the child's own thread
/// with that id has exited, so nothing is left to resume: skipped, not an error. A failed call on
/// the child's own thread is recorded in `last_err`.
fn resume_if_owned(tid: u32, process_pid: u32, walk: &mut Walk) -> Visit {
    use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER};

    let gone = windows::core::HRESULT::from_win32(ERROR_INVALID_PARAMETER.0);
    let denied = windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0);

    let query = match open_query(tid) {
        Ok(h) => h,
        Err(e) if e.code() == gone => {
            walk.skip(format!("thread {tid} no longer exists"));
            return Visit::Gone;
        }
        Err(e) if e.code() == denied => {
            walk.skip(format!(
                "thread {tid} cannot be opened for query (access denied), so it is not the child's"
            ));
            return Visit::Denied;
        }
        Err(e) => return walk.fail_win32("OpenThread(query)", tid, process_pid, e),
    };

    match owner_of(&query) {
        Ok(owner) if owner == process_pid => {}
        Ok(owner) => {
            walk.skip(format!("thread {tid} now belongs to pid {owner}"));
            return Visit::Foreign { owner };
        }
        Err(e) => return walk.fail_win32("GetProcessIdOfThread", tid, process_pid, e),
    }

    let resume = match open_for_resume(tid) {
        Ok(h) => h,
        Err(e) => return walk.fail_win32("OpenThread(suspend/resume)", tid, process_pid, e),
    };
    match owner_of(&resume) {
        Ok(again) if again == process_pid => {}
        Ok(again) => {
            return walk.fail(
                "OpenThread(suspend/resume)",
                tid,
                process_pid,
                format_args!("opened a thread of pid {again}, not the thread just checked"),
            )
        }
        Err(e) => return walk.fail_win32("GetProcessIdOfThread", tid, process_pid, e),
    }

    match resume_thread(&resume) {
        Ok(1) => {
            walk.resumed += 1;
            Visit::Resumed
        }
        Ok(_) if walk.expected == SuspendCount::Any => {
            walk.resumed += 1;
            Visit::Resumed
        }
        // Anything else leaves a process that is not running the way its creator left it. A count
        // above 1 is an initial thread still suspended after this resume (a debugger, an EDR agent
        // or the caller's own tooling suspended it in the window); 0 is an initial thread that was
        // already running, so the child ran before it was released.
        Ok(previous) => walk.fail(
            "ResumeThread",
            tid,
            process_pid,
            format_args!(
                "the previous suspend count was {previous}, not 1: {}",
                if previous > 1 {
                    "the thread is still suspended"
                } else {
                    "the thread was not suspended, so the child had already run"
                }
            ),
        ),
        Err(e) => walk.fail_win32("ResumeThread", tid, process_pid, e),
    }
}

/// The creation time of thread `tid` (100 ns ticks) if it is a thread of `process_pid`; `None` if
/// the id is stale (gone, another process's, not openable by the child's creator). The error names
/// the failed call.
fn creation_time_if_owned(tid: u32, process_pid: u32) -> Result<Option<u64>, (&'static str, windows::core::Error)> {
    use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, FILETIME};
    use windows::Win32::System::Threading::GetThreadTimes;

    let gone = windows::core::HRESULT::from_win32(ERROR_INVALID_PARAMETER.0);
    let denied = windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0);

    // SAFETY: plain Win32 call; the handle is owned by the returned guard, which pins the thread.
    let thread = match unsafe { OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, tid) } {
        Ok(h) => ThreadHandle(h),
        Err(e) if e.code() == gone || e.code() == denied => return Ok(None),
        Err(e) => return Err(("OpenThread(query)", e)),
    };
    match owner_of(&thread) {
        Ok(owner) if owner == process_pid => {}
        Ok(_) => return Ok(None),
        Err(e) => return Err(("GetProcessIdOfThread", e)),
    }
    let (mut created, mut exited, mut kernel, mut user) = (
        FILETIME::default(),
        FILETIME::default(),
        FILETIME::default(),
        FILETIME::default(),
    );
    #[cfg(test)]
    forced(fault::Step::CreationTime, Some(tid)).map_err(|e| ("GetThreadTimes", e))?;
    // SAFETY: `thread` is a live handle with THREAD_QUERY_LIMITED_INFORMATION; the out-parameters
    // are valid.
    unsafe { GetThreadTimes(thread.0, &mut created, &mut exited, &mut kernel, &mut user) }
        .map_err(|e| ("GetThreadTimes", e))?;
    #[cfg(test)]
    if fault::creation_times_are_equal() {
        return Ok(Some(1));
    }
    Ok(Some(
        (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime),
    ))
}

/// The id of the child's initial thread among `tids`: the thread of `process_pid` created first.
///
/// A frozen child has one thread, its initial one, until someone else starts another; a thread
/// created later has a later creation time. Thread ids say nothing about order, and the snapshot
/// lists threads in no promised order.
///
/// `None`, with the cause in `walk`, when the initial thread cannot be told: the snapshot lists no
/// thread of the child, every listed thread is stale, the creation time of a thread of the child
/// cannot be read (it might be the earlier), or the earliest two are equal. The
/// clock was measured only on Windows 11 10.0.26100, where 300 threads started back to back in one
/// process were 56 us or more apart; whether an older build's clock can tie is unmeasured, so a tie
/// is a failure, never a guess by thread id.
fn initial_thread_id(process_pid: u32, tids: &[u32], walk: &mut Walk) -> Option<u32> {
    let mut times = Vec::with_capacity(tids.len());
    for &tid in tids {
        match creation_time_if_owned(tid, process_pid) {
            Ok(Some(created)) => times.push((created, tid)),
            Ok(None) => walk.skip(format!(
                "thread {tid} is gone, is not pid {process_pid}'s, or cannot be opened by the child's creator"
            )),
            Err((call, e)) => {
                walk.fail_win32(call, tid, process_pid, e);
                return None;
            }
        }
    }
    match earliest_created(times) {
        Earliest::NoThread => None,
        Earliest::Unique(tid) => Some(tid),
        Earliest::Tie(first, second) => {
            walk.fail_unidentified(process_pid, first, second);
            None
        }
    }
}

/// Which of some `(creation time, thread id)` pairs is the earliest.
#[derive(Debug, PartialEq, Eq)]
enum Earliest {
    NoThread,
    Unique(u32),
    /// Two threads share the earliest time, in the order they were listed: which came first is
    /// unknowable.
    Tie(u32, u32),
}

fn earliest_created(times: impl IntoIterator<Item = (u64, u32)>) -> Earliest {
    let mut best: Option<(u64, u32)> = None;
    let mut tied: Option<u32> = None;
    for (created, tid) in times {
        match best {
            Some((time, _)) if created > time => {}
            Some((time, _)) if created == time => {
                tied.get_or_insert(tid);
            }
            _ => {
                best = Some((created, tid));
                tied = None;
            }
        }
    }
    match (best, tied) {
        (None, _) => Earliest::NoThread,
        (Some((_, tid)), None) => Earliest::Unique(tid),
        (Some((_, first)), Some(second)) => Earliest::Tie(first, second),
    }
}

/// The pid of the process at `raw_handle`, or an error naming `GetProcessId` that keeps its Win32
/// code as its source.
///
/// `GetProcessId` answers 0 on failure, and a walk filtered to owner 0 would match the System
/// Idle process instead of the child.
fn process_pid_of(raw_handle: HANDLE) -> io::Result<u32> {
    // SAFETY: `GetProcessId` only reads the handle; an invalid one is reported as 0.
    let pid = unsafe { GetProcessId(raw_handle) };
    if pid == 0 {
        return Err(io_context(
            "GetProcessId failed on the child's handle",
            io::Error::last_os_error(),
        ));
    }
    Ok(pid)
}

/// The error for a walk that resumed nothing, naming why every listed thread was skipped.
fn none_resumed_error(process_pid: u32, last_skip: Option<&str>) -> io::Error {
    match last_skip {
        Some(reason) => io::Error::other(format!(
            "no suspended threads resumed: every thread the snapshot listed for pid {process_pid} was stale (last: {reason})"
        )),
        None => io::Error::other(format!(
            "no suspended threads resumed: the snapshot listed no threads for pid {process_pid}"
        )),
    }
}

/// The outcome of a finished walk. A failed resume is an error even when siblings resumed: a
/// thread left suspended is exactly the "frozen process" `resume_initial_threads` exists to rule
/// out, however many of its siblings got moving first.
fn walk_verdict(process_pid: u32, walk: Walk) -> io::Result<()> {
    let Walk {
        resumed,
        last_err,
        last_skip,
        ..
    } = walk;
    if let Some(e) = last_err {
        log::warn!(
            "resume_initial_threads: failed to resume one or more of this child's initial threads \
             ({resumed} resumed successfully before the failure): {e}"
        );
        return Err(e);
    }
    if resumed == 0 {
        return Err(none_resumed_error(process_pid, last_skip.as_deref()));
    }
    Ok(())
}

/// Resume every suspended thread of the process at `proc_handle` after job assignment.
///
/// Why resume REGARDLESS of job-assign result: the kill-group race invariant
/// requires the child to be inside the job before executing, so it was spawned
/// frozen (CREATE_SUSPENDED). Whether or not job assignment succeeded, the child
/// MUST be resumed — a frozen process is unacceptable. If `ResumeThread` fails
/// the child is killed immediately and an error returned.
///
/// `expected` is what each resume's previous suspend count must be; see [`SuspendCount`].
///
/// PID-reuse safety: the caller holds the child's process handle (via the owning
/// `Child`), keeping its PID alive for the duration of the Toolhelp snapshot walk.
pub(crate) fn resume_initial_threads(
    proc_handle: std::os::windows::io::RawHandle,
    expected: SuspendCount,
) -> io::Result<()> {
    use windows::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD};

    let raw_handle = HANDLE(proc_handle.cast());

    let mut walk = Walk {
        expected,
        ..Walk::default()
    };

    let process_pid = process_pid_of(raw_handle);
    debug_assert!(
        process_pid.is_ok(),
        "the caller must pass a live process handle: {process_pid:?}"
    );
    let process_pid = process_pid?;

    // SAFETY: snapshot/iterate with an owned handle, closed before return.
    unsafe {
        let snap = thread_snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0))?;
        let entries = thread_entries_closing(snap)?;

        if walk.expected == SuspendCount::ExactlyOne {
            // Only the initial thread is resumed. The others are opened query-only, to read their
            // creation time, and that read failing fails the release.
            let own: Vec<u32> = entries
                .iter()
                .filter(|e| e.th32OwnerProcessID == process_pid)
                .map(|e| e.th32ThreadID)
                .collect();
            if let Some(initial) = initial_thread_id(process_pid, &own, &mut walk) {
                resume_if_owned(initial, process_pid, &mut walk);
            }
        } else {
            for entry in &entries {
                visit_thread_entry(entry, process_pid, &mut walk);
            }
        }
    }

    // Test-only: the injected entry goes through the same owner filter as a real one.
    #[cfg(test)]
    if let Some((tid, owner)) = fault::injected_entry() {
        let entry = windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32 {
            th32OwnerProcessID: owner.unwrap_or(process_pid),
            th32ThreadID: tid,
            ..Default::default()
        };
        fault::record_injected_visit(visit_thread_entry(&entry, process_pid, &mut walk));
    }

    walk_verdict(process_pid, walk)
}

/// Assign the process at `proc_handle` to a `KILL_ON_JOB_CLOSE` job and resume its
/// initial threads.
///
/// `proc_handle` must remain open for the whole call (it pins the pid against reuse during the
/// Toolhelp thread walk in `resume_initial_threads`). Both callers hold the owning `Child` —
/// sync `std::process::Child`, async `::tokio::process::Child` — across the call, so it does.
///
/// Returns `Ok(Some(JobHandle))` on full success (job assigned AND resumed).
/// Returns `Ok(None)` when job assignment fails — the caller falls back to the
/// universal `Containment::TreeWalk` mechanism (identity teardown).
/// Returns `Err` when resume fails — a frozen child is unacceptable; the
/// child+job are killed and the error propagates to fail the spawn.
pub(crate) fn attach_job(proc_handle: std::os::windows::io::RawHandle) -> io::Result<Option<JobHandle>> {
    let job_result = assign_held(proc_handle);

    // Resume REGARDLESS of job assignment result. A frozen child cannot be left running.
    if let Err(resume_err) = resume_initial_threads(proc_handle, SuspendCount::Any) {
        if let Ok(job) = job_result {
            // Kill via the job first (catches any threads the walk may have missed). The
            // resume failure is what gets reported; a kill failure on top of it cannot change
            // that outcome, so it is logged here rather than swallowed.
            if let Err(e) = job.hard_kill() {
                log::warn!("job kill after a failed resume also failed ({e}); the tree may still be running");
            }
        }
        return Err(resume_err);
    }

    match job_result {
        Ok(job) => Ok(Some(job)),
        Err(_e) => {
            // Job assignment failed. Surfaced to the caller as Ok(None); dispatch
            // falls back to the TreeWalk mechanism. A library must not write to
            // the parent's stderr unconditionally.
            Ok(None)
        }
    }
}

/// Test-only membership probe: whether `pid` is inside the Job Object held by `attached`, via
/// `IsProcessInJob` against that job handle (not "any job"). Membership is immutable once assigned,
/// so it is deterministic for a handle-pinned child regardless of run state. Shared by the sync and
/// async `Child::test_job_handle_contains_self` accessors (both compiled outside `cfg(test)` so
/// integration crates can call them).
pub(crate) fn job_contains_pid(attached: &crate::containment::Attached, pid: u32) -> bool {
    use windows::Win32::System::JobObjects::IsProcessInJob;
    use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_INFORMATION};

    let crate::containment::Attached::JobObject(job) = attached else {
        return false;
    };

    // Open the child process by PID; the backend doesn't expose its handle.
    // SAFETY: standard Win32 call; the handle is closed below.
    let process_handle = unsafe {
        match OpenProcess(PROCESS_QUERY_INFORMATION, false, pid) {
            Ok(h) => h,
            Err(_) => return false,
        }
    };

    let mut in_job = windows::core::BOOL(0);
    // Lock held across the query so the job handle cannot be closed and its value recycled
    // between the read and the call.
    let queried = job.with_handle(|job_handle| {
        // SAFETY: both handles are valid for the duration of the call.
        unsafe { IsProcessInJob(process_handle, Some(job_handle), &mut in_job) }
    });
    // SAFETY: `process_handle` was opened above and must be closed.
    unsafe {
        _ = CloseHandle(process_handle);
    }
    matches!(queried, Some(Ok(()))) && in_job.as_bool()
}

/// The limit flags `job` holds now, or `None` when its handle is already closed.
pub(crate) fn job_limit_flags(
    job: &JobHandle,
) -> Option<windows::core::Result<windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT>> {
    use windows::Win32::System::JobObjects::{JobObjectBasicLimitInformation, JOBOBJECT_BASIC_LIMIT_INFORMATION};

    let mut info = JOBOBJECT_BASIC_LIMIT_INFORMATION::default();
    let queried = job.with_handle(|handle| {
        // SAFETY: `handle` is live for the call, and `info` is a correctly sized out-parameter.
        unsafe {
            QueryInformationJobObject(
                Some(handle),
                JobObjectBasicLimitInformation,
                std::ptr::addr_of_mut!(info).cast(),
                size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,
                None,
            )
        }
    })?;
    Some(queried.map(|()| info.LimitFlags))
}

/// Test-only: whether the Job Object held by `attached` kills its members when its last handle
/// closes. `false` when `attached` is not a job. Panics, naming the cause, when the query fails or
/// the job handle is closed, so a failed query is not read as "no kill-on-close".
pub(crate) fn job_kills_on_close(attached: &crate::containment::Attached) -> bool {
    let crate::containment::Attached::JobObject(job) = attached else {
        return false;
    };
    let flags = job_limit_flags(job)
        .expect("the job handle is closed")
        .unwrap_or_else(|e| panic!("querying the job's limits failed: {e}"));
    flags.0 & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0 != 0
}

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