mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Reusable WSLc SDK building blocks shared by the one-shot `ScriptRunner`
//! ([`crate::wslc_common::wsl_container_runner`]) and the state-aware daemon
//! (`wxc_wslc_daemon::session_manager`).
//!
//! # Why this module exists
//! The one-shot runner builds a `WslcProcessSettings` and a
//! `WslcContainerSettings` inline, then creates the container in a single
//! function whose stack locals keep the backing string/pointer buffers alive.
//! The WSLc SDK **stores raw pointers into those caller buffers** (it does not
//! copy them) and dereferences them at `WslcCreateContainer` /
//! `WslcCreateContainerProcess` time, so the buffers must outlive the create
//! call. In the one-shot path that "outlives" is expressed by stack scope.
//!
//! The state-aware daemon needs the *same* marshalling but across separate
//! phase calls, so the lifetime contract cannot be expressed by a single
//! function's stack. This module reifies each settings blob as a
//! **buffer-owning struct** ([`ProcessSettings`] / [`ContainerSettings`]) that
//! bundles the `Wslc*Settings` value together with every heap buffer its
//! pointers reference. Both callers hold the struct for as long as the SDK
//! needs the pointers valid.
//!
//! # Move safety
//! Every buffer a settings pointer references is heap-allocated (`Vec`, `Arc`)
//! or `'static`. Moving one of these structs copies only the owning headers —
//! the referenced heap allocations do not relocate — so the raw pointers the
//! SDK stored remain valid across a move. The one rule callers must honor:
//! **do not move the struct after handing a `&raw` (or a settings value that
//! embeds a pointer to it, e.g. an init-process settings) to the SDK.** In
//! practice the builders return the fully-populated struct by value (a single
//! move that happens *before* any `&raw` is taken), after which callers keep it
//! as a stationary local.

use std::ffi::{c_void, CStr, CString};
use std::fmt::Write;
use std::net::Ipv4Addr;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{PortMapping, ScriptResponse};
use crate::mxc_common::mxc_error::ApiFailure;
use crate::mxc_common::string_util::{to_wide, CoTaskMemPWSTR};

use crate::wslc_common::daemon_protocol::ExecTerminal;

use crate::wslc_common::error::{sdk_api_failure, WslcError, WslcStepError};
use crate::wslc_common::policy_mapping::VolumeMount;
use crate::wslc_common::process_env::{self, EnvScope};
use crate::wslc_common::sdk_init;
use crate::wslc_common::session_resources;
use crate::wslc_common::wslc_bindings::*;

// ---------------------------------------------------------------------------
// Shared error helper
// ---------------------------------------------------------------------------

/// `ERROR_SHARING_VIOLATION`, which the SDK reports when a call reaches a store
/// whose VHDX another live session already has mounted.
const E_SHARING_VIOLATION: HRESULT = 0x8007_0020_u32 as HRESULT;

/// VM/session boot budget, in milliseconds.
///
/// Deliberately independent of any per-command runtime deadline, so a short
/// command timeout cannot abort a cold VM boot.
pub const SESSION_BOOT_TIMEOUT_MS: u32 = 180_000;

/// How a session's WSL2 utility VM is sized.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SessionSizing {
    /// Virtual CPUs, or `None` for the host default.
    pub cpu_count: Option<u32>,

    /// Memory in MB, or `None` for the host default.
    pub memory_mb: Option<u64>,

    /// Whether to enable GPU passthrough.
    pub gpu: bool,
}

/// What the host has installed, rather than what is currently free.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HostCapacity {
    /// Physical memory installed, in MB.
    pub total_memory_mb: u64,

    /// Logical processors the machine has.
    pub logical_cpus: u32,
}

/// Read what this host has installed.
fn host_capacity() -> Option<HostCapacity> {
    use windows::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
    use windows::Win32::System::Threading::{GetActiveProcessorCount, ALL_PROCESSOR_GROUPS};

    let mut status = MEMORYSTATUSEX {
        dwLength: std::mem::size_of::<MEMORYSTATUSEX>() as u32,
        ..Default::default()
    };

    // SAFETY: `status` is a valid `MEMORYSTATUSEX` whose `dwLength` is set, as
    // the API requires.
    unsafe { GlobalMemoryStatusEx(&mut status) }.ok()?;

    // Every processor group, not just the caller's: `GetSystemInfo` reports one
    // group and caps at 64, so a host with more would refuse a size it can run.
    // A job object narrowing what mxc may run on does not narrow what the
    // hypervisor can give a VM either.
    let logical_cpus = unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) };

    Some(HostCapacity {
        total_memory_mb: status.ullTotalPhys / (1024 * 1024),
        logical_cpus,
    })
}

/// Reject a session asking for more processors than the host has.
///
/// `memory_mb` is deliberately not checked: it is a ceiling the host backs on
/// demand, so asking for more memory than is installed works.
fn sizing_fits_host(sizing: SessionSizing, host: HostCapacity) -> Result<(), ScriptResponse> {
    // The SDK reads `0` as "use the default" rather than as a size.
    let Some(cpu_count) = sizing.cpu_count.filter(|cpus| *cpus > 0) else {
        return Ok(());
    };

    if cpu_count > host.logical_cpus {
        return Err(WslcError::Rejected(format!(
            "cpu_count {cpu_count} exceeds the {} logical processors this host has; \
             WSLc does not oversubscribe processors, though memory_mb may exceed \
             installed memory because it is a ceiling rather than a reservation",
            host.logical_cpus
        ))
        .into_response());
    }

    Ok(())
}

/// Reject a session sized past this host, when the host can be measured.
///
/// A host that cannot be measured is allowed through, since refusing real work
/// over a failed diagnostic call would be the worse failure.
pub fn check_sizing_against_host(sizing: SessionSizing) -> Result<(), ScriptResponse> {
    match host_capacity() {
        Some(host) => sizing_fits_host(sizing, host),
        None => Ok(()),
    }
}

/// Build a `ScriptResponse` error from an HRESULT failure with an optional
/// SDK-provided message. Thin wrapper over [`WslcError::Sdk`], which owns the
/// message formatting and the `LaunchFailed` phase attribution.
pub(crate) fn sdk_error(context: &str, hr: HRESULT, sdk_msg: &str) -> ScriptResponse {
    WslcError::sdk(context, hr, sdk_msg).into_response()
}

pub(crate) fn sdk_step_error(operation: &str, hr: HRESULT, sdk_msg: &str) -> WslcStepError {
    sdk_step_error_with_context(operation, &format!("{operation} failed"), hr, sdk_msg)
}

pub(crate) fn sdk_step_error_with_context(
    operation: &str,
    context: &str,
    hr: HRESULT,
    sdk_msg: &str,
) -> WslcStepError {
    WslcError::sdk(context, hr, sdk_msg)
        .into_step_error()
        .with_api_failure(sdk_api_failure(operation, hr))
}

/// NUL-terminate `value` for a C string the WSLc SDK will read, rejecting an
/// interior NUL instead of letting the SDK silently observe a truncated value.
///
/// The daemon protocol accepts arbitrary JSON strings, so a command, env entry,
/// image, or container path can contain `\u{0}`. Rust keeps such a string whole,
/// but the SDK stops at the first NUL — so validation/logging and execution
/// would disagree about what actually ran. Reject at the marshalling boundary.
pub(crate) fn cstr_bytes(field: &str, value: &str) -> Result<Vec<u8>, ScriptResponse> {
    std::ffi::CString::new(value)
        .map(|c| c.into_bytes_with_nul())
        .map_err(|_| {
            WslcError::Rejected(format!(
                "{field} contains an interior NUL byte, which is not a valid C string"
            ))
            .into_response()
        })
}

// ---------------------------------------------------------------------------
// Process I/O capture plumbing
// ---------------------------------------------------------------------------
//
// # IoContext reference lifecycle (why a kill deliberately leaks)
//
// The SDK's stdout/stderr/exit callbacks each receive a raw `*IoContext`. We
// hand the SDK one `Arc<IoContext>` reference (`Arc::into_raw`) and keep an
// independent `Arc` inside `ProcessSettings`, so the context outlives every
// callback. Reclaiming the SDK's reference safely hinges on exactly one rule:
// **it is freed only from `exit_callback`, and the SDK guarantees no callback
// fires after exit.** That yields three reachable end-states:
//
//   build settings ──fail before create──▶ SdkIoRef::drop frees the ref
//        │                                  (no process exists to call back)
//        â–¼
//   process created ──▶ mark_process_created() disarms SdkIoRef
//        │
//        ├── process exits ──▶ exit_callback fires ──▶ frees the SDK ref
//        │
//        └── process killed, exit_callback never fires ──▶ ref is LEAKED
//            on purpose: freeing it while the SDK might still call back would
//            be use-after-free. A confirmed-unkillable container is quarantined
//            (see `exec_in_container` / session_manager), bounding the leak to
//            that one compromised sandbox.
//
// So `SdkIoRef` guards the pre-adoption window (frees on early failure), and
// after adoption ownership passes to `exit_callback`; the kill path trades a
// bounded, one-time leak for memory safety.

/// Which standard stream a live-output chunk came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutStream {
    Stdout,
    Stderr,
}

/// Optional live-output sink that replaces the capped capture buffers, so a
/// caller that sets one gets empty captured stdout/stderr.
///
/// **Two distinct live-output architectures — why they don't share plumbing.**
/// The one-shot runner streams via `OutputMode::Stream` (in `wsl_container_runner`)
/// plus a synchronous in-process `stream_pair`/`StreamReader` (in `stream_buffer`),
/// drained in the same process (caller pipes, or an `inherit_pump` thread). The
/// daemon cannot reuse that: it must relay output across a named pipe to a
/// *separate* client process through an async (tokio) control server, so it
/// bridges the synchronous SDK callback thread to the async pipe writer with a
/// bounded mpsc channel (see `session_manager::enqueue_output`). Their
/// backpressure invariants also differ deliberately: the one-shot `StreamReader`
/// is drained synchronously in-process, whereas this callback **must never
/// block** — the same SDK thread also delivers the process-exit callback, so the
/// daemon path uses a non-blocking `try_send` that drops on overflow rather than
/// stalling teardown. Keep the two paths separate for those reasons; share only
/// the leaf primitives ([`OutStream`], [`IoContext`]).
pub type OutputSink = Box<dyn Fn(OutStream, &[u8]) + Send + Sync>;

/// Takes a process's stdin write end once the process exists and returns
/// control over it.
pub type StdinConsumer =
    Box<dyn FnOnce(std::fs::File) -> std::io::Result<Box<dyn StdinControl>> + Send>;

/// Control over a process's stdin after a [`StdinConsumer`] has taken it.
pub trait StdinControl: Send {
    /// Stop giving the process input or end-of-file, leaving stdin open.
    fn freeze(&self);

    /// Close stdin now, dropping input not yet written.
    fn close(self: Box<Self>);
}

/// Shared buffer for capturing process I/O via SDK callbacks. Fields are
/// `pub(crate)` so the one-shot runner's wait/collect helpers can read the
/// captured bytes and exit signal.
pub struct IoContext {
    pub(crate) stdout: Arc<Mutex<Vec<u8>>>,
    pub(crate) stderr: Arc<Mutex<Vec<u8>>>,
    pub(crate) exited: Arc<(Mutex<bool>, Condvar)>,
    /// Live sink for streaming output; `None` when the caller wants the final
    /// captured blob instead. A streaming caller reads its bytes from the sink
    /// as they arrive, so the capture buffers stay empty. Its owning
    /// `Arc<IoContext>` is released on the same schedule as those buffers, so
    /// on the deliberate kill-path leak the sink (and its sender) is leaked too.
    sink: Option<OutputSink>,
    capture: Capture,
}

/// Per-stream cap on captured stdout/stderr, in bytes. The WSLc SDK streams
/// output from untrusted in-container code straight into these buffers; without
/// a ceiling one exec could grow them without bound and OOM the persistent
/// daemon, taking down every sandbox it owns. When a stream reaches the cap the
/// tail is dropped and a one-time truncation marker is appended.
const MAX_CAPTURED_STREAM_BYTES: usize = 8 * 1024 * 1024;

/// Appended once to a captured stream when it first hits the cap, so a consumer
/// can tell the output was truncated rather than genuinely ending there.
const STREAM_TRUNCATION_MARKER: &[u8] = b"\n[output truncated: stream exceeded capture cap]\n";

/// Append `bytes` to a captured stream buffer, enforcing
/// [`MAX_CAPTURED_STREAM_BYTES`]. Once the cap is reached the buffer stops
/// growing; the marker is appended exactly once, on the call that crosses it.
fn append_capped(buf: &mut Vec<u8>, bytes: &[u8]) {
    if buf.len() >= MAX_CAPTURED_STREAM_BYTES {
        return;
    }
    let remaining = MAX_CAPTURED_STREAM_BYTES - buf.len();
    if bytes.len() <= remaining {
        buf.extend_from_slice(bytes);
    } else {
        buf.extend_from_slice(&bytes[..remaining]);
        buf.extend_from_slice(STREAM_TRUNCATION_MARKER);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Capture {
    Head,
    Tail(usize),
}

impl Capture {
    fn append(self, buf: &mut Vec<u8>, bytes: &[u8]) {
        match self {
            Capture::Head => append_capped(buf, bytes),
            Capture::Tail(limit) => append_newest(buf, bytes, limit),
        }
    }
}

fn append_newest(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
    buf.extend_from_slice(bytes);
    if buf.len() <= limit {
        return;
    }
    let excess = buf.len() - limit;
    let first_whole_line = buf[excess - 1..]
        .iter()
        .position(|&b| b == b'\n')
        .map_or(excess, |offset| excess + offset);
    buf.drain(..first_whole_line);
}

/// Callback invoked by the WSLc SDK for stdout/stderr data.
///
/// # Safety
/// `context` must be a valid pointer obtained from `Arc::into_raw(Arc<IoContext>)`.
/// The `Arc` reference handed to the SDK is released inside [`exit_callback`]; the
/// SDK guarantees no I/O callback fires after exit, and the owning
/// [`ProcessSettings`] holds an independent reference, so the pointer stays valid
/// for every callback. The SDK guarantees `data` is valid for `data_size` bytes.
unsafe extern "C" fn io_callback(
    io_handle: WslcProcessIOHandle,
    data: *const BYTE,
    data_size: u32,
    context: *mut c_void,
) {
    if context.is_null() || data.is_null() || data_size == 0 {
        return;
    }
    let ctx = &*(context as *const IoContext);
    let bytes = std::slice::from_raw_parts(data, data_size as usize);
    match io_handle {
        WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDOUT => match ctx.sink.as_ref() {
            Some(sink) => sink(OutStream::Stdout, bytes),
            None => {
                let mut buf = ctx.stdout.lock().unwrap_or_else(|e| e.into_inner());
                ctx.capture.append(&mut buf, bytes);
            }
        },
        WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDERR => match ctx.sink.as_ref() {
            Some(sink) => sink(OutStream::Stderr, bytes),
            None => {
                let mut buf = ctx.stderr.lock().unwrap_or_else(|e| e.into_inner());
                ctx.capture.append(&mut buf, bytes);
            }
        },
        _ => {}
    }
}

/// Callback invoked when the process exits and all I/O has been flushed.
/// Per SDK docs: "Once this callback is invoked, any registered IO callbacks
/// will no longer be called." This guarantees buffers are complete and that the
/// SDK will not touch `context` again, so this reclaims the `Arc` reference the
/// SDK was handed.
///
/// # Safety
/// `context` must be the pointer handed to `WslcSetProcessSettingsCallbacks`,
/// obtained from `Arc::into_raw(Arc<IoContext>)`, and must be invoked at most
/// once.
unsafe extern "C" fn exit_callback(_exit_code: i32, context: *mut c_void) {
    if context.is_null() {
        return;
    }
    // Reclaim the SDK's reference. The owning `ProcessSettings` holds its own
    // reference, so the `IoContext` stays alive for the waiting thread.
    let ctx = Arc::from_raw(context as *const IoContext);
    let mut exited = ctx.exited.0.lock().unwrap_or_else(|e| e.into_inner());
    *exited = true;
    ctx.exited.1.notify_all();
}

/// The command-line and environment buffers the SDK stored pointers into.
///
/// The SDK does not copy them, so this must outlive the create call that reads
/// them.
pub(crate) struct CommandLineBuffers {
    _argv_cstrings: Vec<Vec<u8>>,
    _argv: Vec<PCSTR>,
    _env_cstrings: Vec<Vec<u8>>,
    _env_ptrs: Vec<PCSTR>,
}

/// Set `settings`' command line and environment from `script_code` and `env`
/// applied at `scope`, returning the buffers the SDK now points into.
///
/// # Safety
/// `sdk` must hold valid, currently-loaded function pointers, and `settings`
/// must remain at a fixed address while the returned buffers are alive.
pub(crate) unsafe fn set_command_line_and_env(
    sdk: &WslcSdk,
    settings: *mut WslcProcessSettings,
    scope: EnvScope,
    env: &[String],
    script_code: &str,
) -> Result<CommandLineBuffers, WslcStepError> {
    set_argv_and_env(
        sdk,
        settings,
        &process_env::argv_words(scope, env, script_code),
        &process_env::sdk_entries(scope, env),
    )
}

/// Set `settings`' argv and the environment the SDK layers over the image's.
///
/// # Safety
/// Same contract as [`set_command_line_and_env`].
unsafe fn set_argv_and_env(
    sdk: &WslcSdk,
    settings: *mut WslcProcessSettings,
    argv: &[String],
    env: &[String],
) -> Result<CommandLineBuffers, WslcStepError> {
    let argv_cstrings = argv
        .iter()
        .map(|word| cstr_bytes("command", word))
        .collect::<Result<Vec<_>, _>>()?;
    let argv: Vec<PCSTR> = argv_cstrings.iter().map(|w| w.as_ptr() as PCSTR).collect();
    let hr = sdk.WslcSetProcessSettingsCmdLine(settings, argv.as_ptr(), argv.len());
    if hr != S_OK {
        return Err(sdk_step_error("WslcSetProcessSettingsCmdLine", hr, ""));
    }

    let env_cstrings: Vec<Vec<u8>> = env
        .iter()
        .map(|e| cstr_bytes("environment variable", e))
        .collect::<Result<Vec<_>, _>>()?;
    let mut env_ptrs: Vec<PCSTR> = Vec::new();
    if !env_cstrings.is_empty() {
        env_ptrs = env_cstrings.iter().map(|e| e.as_ptr() as PCSTR).collect();
        let hr =
            sdk.WslcSetProcessSettingsEnvVariables(settings, env_ptrs.as_ptr(), env_ptrs.len());
        if hr != S_OK {
            return Err(sdk_step_error("WslcSetProcessSettingsEnvVariables", hr, ""));
        }
    }

    Ok(CommandLineBuffers {
        _argv_cstrings: argv_cstrings,
        _argv: argv,
        _env_cstrings: env_cstrings,
        _env_ptrs: env_ptrs,
    })
}

// ---------------------------------------------------------------------------
// ProcessSettings builder
// ---------------------------------------------------------------------------

/// A fully-populated `WslcProcessSettings` together with every heap buffer its
/// pointers reference (cmdline argv, env, working dir) and the I/O-capture
/// context. Safe to move (all referenced data is heap/`'static`); do not move
/// after taking `&raw`.
pub struct ProcessSettings {
    raw: WslcProcessSettings,
    io_ctx: Arc<IoContext>,
    // Reclaims the SDK's `IoContext` reference if settings build or process
    // creation fails before a live process adopts it. Disarmed by
    // `mark_process_created` once a process is created, after which
    // `exit_callback` (or a deliberate leak on kill) owns reclamation.
    sdk_io_ref: SdkIoRef,
    // Backing buffers the SDK stored raw pointers into (it does not copy them)
    // and dereferences at `WslcCreateContainerProcess` time. They must outlive
    // the create call, so the struct owns them; the `_` prefix marks them as
    // held purely to anchor those lifetimes, never read directly.
    _command: CommandLineBuffers,
    _cwd_cstr: Option<Vec<u8>>,
}

/// Owns an `Arc<IoContext>` reference handed to the SDK and reclaims it on drop
/// unless disarmed. Used both as a local guard while building settings and as
/// the stored owner inside [`ProcessSettings`], so any error path before a live
/// process adopts the reference frees it instead of leaking.
struct SdkIoRef(Option<*const IoContext>);

impl SdkIoRef {
    fn none() -> Self {
        Self(None)
    }

    /// Disarm reclamation, returning the raw pointer (dropped on the floor by the
    /// caller so ownership passes to `exit_callback`).
    fn disarm(&mut self) -> Option<*const IoContext> {
        self.0.take()
    }
}

impl Drop for SdkIoRef {
    fn drop(&mut self) {
        if let Some(p) = self.0.take() {
            // SAFETY: `p` came from `Arc::into_raw`. This runs only when no live
            // process ever adopted the SDK reference (settings build or process /
            // container creation failed), so the SDK will never invoke
            // `exit_callback` for it and reclaiming here is sound.
            unsafe {
                drop(Arc::from_raw(p));
            }
        }
    }
}

impl ProcessSettings {
    /// Build process settings that run `script_code` under `/bin/sh -c`, with
    /// the given `env` (already proxy-adjusted by the caller) applied at `scope`
    /// and `working_directory` (an absolute in-container path, e.g. `/work`;
    /// empty = container default). Registers stdout/stderr/exit capture
    /// callbacks.
    ///
    /// # Safety
    /// `sdk` must hold valid, currently-loaded function pointers and COM must be
    /// initialized on the calling thread.
    pub unsafe fn build(
        sdk: &WslcSdk,
        script_code: &str,
        env: &[String],
        scope: EnvScope,
        working_directory: &str,
        sink: Option<OutputSink>,
    ) -> Result<Self, WslcStepError> {
        Self::build_inner(
            sdk,
            &process_env::argv_words(scope, env, script_code),
            &process_env::sdk_entries(scope, env),
            working_directory,
            true,
            sink,
            Capture::Head,
        )
    }

    /// Like [`build`](Self::build) but registers no stdio callbacks and shares no
    /// `IoContext` with the SDK, for a detached init whose output is never
    /// streamed. [`io_ctx`](Self::io_ctx) is inert for the returned value.
    ///
    /// # Safety
    /// Same contract as [`build`](Self::build).
    pub unsafe fn build_detached(
        sdk: &WslcSdk,
        script_code: &str,
        env: &[String],
        scope: EnvScope,
        working_directory: &str,
    ) -> Result<Self, WslcStepError> {
        Self::build_inner(
            sdk,
            &process_env::argv_words(scope, env, script_code),
            &process_env::sdk_entries(scope, env),
            working_directory,
            false,
            None,
            Capture::Head,
        )
    }

    /// Run `argv` directly, without a shell, with `env` layered over the
    /// image's environment. Output is captured into [`io_ctx`](Self::io_ctx).
    ///
    /// # Safety
    /// Same contract as [`build`](Self::build).
    pub(crate) unsafe fn build_argv(
        sdk: &WslcSdk,
        argv: &[String],
        env: &[String],
        capture: Capture,
    ) -> Result<Self, WslcStepError> {
        Self::build_inner(sdk, argv, env, "", true, None, capture)
    }

    unsafe fn build_inner(
        sdk: &WslcSdk,
        argv: &[String],
        env: &[String],
        working_directory: &str,
        register_callbacks: bool,
        sink: Option<OutputSink>,
        capture: Capture,
    ) -> Result<Self, WslcStepError> {
        let mut raw = std::mem::zeroed::<WslcProcessSettings>();
        let hr = sdk.WslcInitProcessSettings(&mut raw);
        if hr != S_OK {
            return Err(sdk_step_error("WslcInitProcessSettings", hr, ""));
        }

        let io_ctx = Arc::new(IoContext {
            stdout: Arc::new(Mutex::new(Vec::new())),
            stderr: Arc::new(Mutex::new(Vec::new())),
            exited: Arc::new((Mutex::new(false), Condvar::new())),
            sink,
            capture,
        });

        // Callbacks are registered only for the streamed path; a detached init
        // shares no IoContext with the SDK and mints no extra reference. The
        // SDK's reference is reclaimed inside `exit_callback`, so a process that
        // is killed without its exit callback firing deliberately leaks the
        // reference rather than freeing it while the SDK may still call back.
        // Until a process actually adopts the reference, `sdk_io_ref` guards it
        // so any early return below frees it instead of leaking.
        let mut sdk_io_ref = SdkIoRef::none();
        if register_callbacks {
            let io_ctx_raw = Arc::into_raw(Arc::clone(&io_ctx)) as *mut c_void;
            let callbacks = WslcProcessCallbacks {
                onStdOut: Some(io_callback),
                onStdErr: Some(io_callback),
                onExit: Some(exit_callback),
            };
            let hr = sdk.WslcSetProcessSettingsCallbacks(&mut raw, &callbacks, io_ctx_raw);
            if hr != S_OK {
                // The SDK never took ownership; reclaim the reference now.
                drop(Arc::from_raw(io_ctx_raw as *const IoContext));
                return Err(sdk_step_error("WslcSetProcessSettingsCallbacks", hr, ""));
            }
            sdk_io_ref = SdkIoRef(Some(io_ctx_raw as *const IoContext));
        }

        let command = set_argv_and_env(sdk, &mut raw, argv, env)?;

        // Working directory (an absolute in-container path, e.g. `/work`; empty =
        // container default). It is passed straight to the SDK; a non-absolute
        // value is rejected rather than silently ignored.
        let mut cwd_cstr: Option<Vec<u8>> = None;
        if !working_directory.is_empty() {
            if !working_directory.starts_with('/') {
                return Err(WslcError::Rejected(format!(
                    "working_directory must be an absolute in-container path (got {working_directory:?})"
                ))
                .into());
            }
            let c = cstr_bytes("working_directory", working_directory)?;
            let hr = sdk.WslcSetProcessSettingsWorkingDirectory(&mut raw, c.as_ptr() as PCSTR);
            if hr != S_OK {
                return Err(sdk_step_error(
                    "WslcSetProcessSettingsWorkingDirectory",
                    hr,
                    "",
                ));
            }
            cwd_cstr = Some(c);
        }

        Ok(ProcessSettings {
            raw,
            io_ctx,
            sdk_io_ref,
            _command: command,
            _cwd_cstr: cwd_cstr,
        })
    }

    /// Transfer ownership of the SDK's `IoContext` reference to the newly-created
    /// process. After this, `Drop` will not reclaim it — `exit_callback` (or a
    /// deliberate leak on kill) owns reclamation, preserving the invariant that
    /// the reference is never freed while the SDK may still call back.
    ///
    /// # Safety
    /// Call exactly once, immediately after a process has been successfully
    /// created from these settings (`WslcCreateContainerProcess`, or
    /// `WslcCreateContainer` + `WslcStartContainer` when used as a container
    /// init). Skipping this after a successful create would let `Drop` free a
    /// reference the SDK still owns.
    pub unsafe fn mark_process_created(&mut self) {
        let _ = self.sdk_io_ref.disarm();
    }

    /// The I/O-capture context shared with the SDK callbacks.
    pub fn io_ctx(&self) -> &IoContext {
        &self.io_ctx
    }

    /// Mutable raw settings pointer for `WslcSetContainerSettingsInitProcess` /
    /// `WslcCreateContainerProcess`. Do not move `self` after calling this.
    pub fn raw_mut(&mut self) -> &mut WslcProcessSettings {
        &mut self.raw
    }
}

// ---------------------------------------------------------------------------
// ContainerSettings builder
// ---------------------------------------------------------------------------

/// IPv4 `127.0.0.1` as a `sockaddr_in` (port, then address, in network order).
/// `'static` because the SDK reads `windowsAddress` at `WslcCreateContainer`.
static WINDOWS_LOOPBACK: sockaddr_storage = sockaddr_storage {
    ss_family: 2, // AF_INET
    __ss_pad1: [0, 0, 127, 0, 0, 1],
    __ss_align: 0,
    __ss_pad2: [0; 112],
};

/// The SDK form of `mappings`, bound to Windows `127.0.0.1` only.
/// The parser rejects UDP today; the branch keeps this correct if an SDK
/// update enables it.
pub(crate) fn sdk_port_mappings(mappings: &[PortMapping]) -> Vec<WslcContainerPortMapping> {
    mappings
        .iter()
        .map(|pm| WslcContainerPortMapping {
            windowsPort: pm.windows_port,
            containerPort: pm.container_port,
            protocol: if pm.protocol == "udp" {
                WslcPortProtocol::WSLC_PORT_PROTOCOL_UDP
            } else {
                WslcPortProtocol::WSLC_PORT_PROTOCOL_TCP
            },
            // The SDK only reads the address.
            windowsAddress: ptr::from_ref(&WINDOWS_LOOPBACK).cast_mut(),
        })
        .collect()
}

/// How a container joins the network.
#[derive(Clone, Copy, Debug)]
pub enum ContainerNetworking<'a> {
    /// No network interface.
    None,
    /// The session's shared NAT network.
    Nat,
    /// A network of its own, with NAT.
    Network(&'a CStr),
    /// Behind the built-in proxy, at a pinned address on its internal network.
    Proxied {
        name: &'a CStr,
        network: &'a CStr,
        address: Ipv4Addr,
    },
}

/// A fully-populated `WslcContainerSettings` together with every heap buffer its
/// pointers reference (image name, volume paths, port mappings, networks). The
/// init process is intentionally NOT set here — that is caller-specific (the
/// one-shot path bakes the script as init; the daemon uses a keepalive init) and
/// is applied by the caller before `WslcCreateContainer`.
pub struct ContainerSettings {
    raw: WslcContainerSettings,
    _image_cstr: Vec<u8>,
    _wide_paths: Vec<(Vec<u16>, Vec<u8>)>,
    _volumes: Vec<WslcContainerVolume>,
    _port_mappings: Vec<WslcContainerPortMapping>,
    _names: Vec<CString>,
    _address: Option<Box<IN_ADDR>>,
    _networks: Vec<WslcContainerNetwork>,
    _capability_drops: Vec<PCSTR>,
}

impl ContainerSettings {
    /// Build container settings for `image` with the given volume `mounts`,
    /// `port_mappings`, `networking`, and container `flags`. The caller
    /// computes them from policy and applies the init process afterward.
    ///
    /// # Safety
    /// `sdk` must hold valid, currently-loaded function pointers.
    pub unsafe fn build(
        sdk: &WslcSdk,
        image: &str,
        mounts: &[VolumeMount],
        port_mappings: &[PortMapping],
        networking: ContainerNetworking,
        flags: WslcContainerFlags,
        logger: &mut Logger,
    ) -> Result<Self, WslcStepError> {
        let image_cstr = cstr_bytes("image", image)?;
        let mut raw = std::mem::zeroed::<WslcContainerSettings>();
        let hr = sdk.WslcInitContainerSettings(image_cstr.as_ptr() as PCSTR, &mut raw);
        if hr != S_OK {
            return Err(sdk_step_error("WslcInitContainerSettings", hr, ""));
        }

        // Port mappings (host<->container). Empty list = no forwarding.
        let mut port_vec: Vec<WslcContainerPortMapping> = Vec::new();
        if !port_mappings.is_empty() {
            port_vec = sdk_port_mappings(port_mappings);

            let hr = sdk.WslcSetContainerSettingsPortMappings(
                &mut raw,
                port_vec.as_ptr(),
                port_vec.len() as u32,
            );
            if hr != S_OK {
                return Err(sdk_step_error(
                    "WslcSetContainerSettingsPortMappings",
                    hr,
                    "",
                ));
            }
            let _ = writeln!(
                logger,
                "[WSLC] {} port mapping(s) configured",
                port_vec.len()
            );
        }

        // Volume mounts. wide_paths owns the widened Windows paths + NUL-
        // terminated container paths the volume pointers reference.
        let wide_paths: Vec<(Vec<u16>, Vec<u8>)> = mounts
            .iter()
            .map(|m| {
                let win: Vec<u16> = to_wide(&m.windows_path);
                let ctr: Vec<u8> = cstr_bytes("mount container_path", &m.container_path)?;
                Ok((win, ctr))
            })
            .collect::<Result<Vec<_>, ScriptResponse>>()?;

        let mut volumes: Vec<WslcContainerVolume> = Vec::new();
        if !mounts.is_empty() {
            volumes = wide_paths
                .iter()
                .zip(mounts.iter())
                .map(|((win, ctr), m)| WslcContainerVolume {
                    windowsPath: win.as_ptr(),
                    containerPath: ctr.as_ptr() as PCSTR,
                    readOnly: if m.read_only { 1 } else { 0 },
                })
                .collect();

            let hr = sdk.WslcSetContainerSettingsVolumes(
                &mut raw,
                volumes.as_ptr(),
                volumes.len() as u32,
            );
            if hr != S_OK {
                return Err(sdk_step_error("WslcSetContainerSettingsVolumes", hr, ""));
            }
            let _ = writeln!(
                logger,
                "[WSLC] {} volume mount(s) configured",
                volumes.len()
            );
        }

        let mut names = Vec::new();
        let mut address = None;
        let mut networks = Vec::new();
        let mut capability_drops = Vec::new();
        let mode = match networking {
            ContainerNetworking::None => {
                Some(WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_NONE)
            }
            ContainerNetworking::Nat => {
                Some(WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_BRIDGED)
            }
            ContainerNetworking::Network(network) => {
                names.push(network.to_owned());
                networks.push(session_resources::network(&names[0], ptr::null()));
                let _ = writeln!(logger, "[WSLC] Network: {}", network.to_string_lossy());
                None
            }
            ContainerNetworking::Proxied {
                name,
                network,
                address: ip,
            } => {
                names.extend([name.to_owned(), network.to_owned()]);
                let hr = sdk.WslcSetContainerSettingsName(&mut raw, names[0].as_ptr());
                if hr != S_OK {
                    return Err(sdk_step_error("WslcSetContainerSettingsName", hr, ""));
                }
                let ip: &IN_ADDR = address.insert(Box::new(session_resources::in_addr_of(ip)));
                networks.push(session_resources::network(&names[1], ip));
                // Raw sockets could hand frames to the gateway outside the proxy.
                capability_drops.push(c"NET_RAW".as_ptr());
                let hr = sdk.WslcSetContainerSettingsCapabilityDrops(
                    &mut raw,
                    capability_drops.as_ptr(),
                    capability_drops.len() as u32,
                );
                if hr != S_OK {
                    return Err(sdk_step_error(
                        "WslcSetContainerSettingsCapabilityDrops",
                        hr,
                        "",
                    ));
                }
                let _ = writeln!(logger, "[WSLC] Networking: built-in proxy");
                None
            }
        };
        if let Some(mode) = mode {
            let hr = sdk.WslcSetContainerSettingsNetworkingMode(&mut raw, mode);
            if hr != S_OK {
                return Err(sdk_step_error(
                    "WslcSetContainerSettingsNetworkingMode",
                    hr,
                    "",
                ));
            }
            let _ = writeln!(logger, "[WSLC] Networking mode: {:?}", mode);
        }
        if !networks.is_empty() {
            let hr = sdk.WslcSetContainerSettingsNetworks(
                &mut raw,
                networks.as_ptr(),
                networks.len() as u32,
            );
            if hr != S_OK {
                return Err(sdk_step_error("WslcSetContainerSettingsNetworks", hr, ""));
            }
        }

        let hr = sdk.WslcSetContainerSettingsFlags(&mut raw, flags);
        if hr != S_OK {
            return Err(sdk_step_error("WslcSetContainerSettingsFlags", hr, ""));
        }

        Ok(ContainerSettings {
            raw,
            _image_cstr: image_cstr,
            _wide_paths: wide_paths,
            _volumes: volumes,
            _port_mappings: port_vec,
            _names: names,
            _address: address,
            _networks: networks,
            _capability_drops: capability_drops,
        })
    }

    /// Mutable raw settings for `WslcSetContainerSettingsInitProcess`.
    /// Do not move `self` after calling this.
    pub fn raw_mut(&mut self) -> &mut WslcContainerSettings {
        &mut self.raw
    }

    /// Shared raw settings for `WslcCreateContainer`.
    pub fn raw(&self) -> &WslcContainerSettings {
        &self.raw
    }
}

// ---------------------------------------------------------------------------
// State-aware daemon steps
// ---------------------------------------------------------------------------
//
// The one-shot runner expresses each phase (session → image → container →
// process → wait) as stack scope inside `run_internal`. The state-aware daemon
// (`wxc_wslc_daemon::session_manager`) drives the *same* SDK sequence but across
// separate provision/start/exec/stop/deprovision calls, so each step is reified
// as a standalone `pub unsafe fn` here. These wrappers keep every raw
// [`IoContext`] / SDK-buffer access inside `wslc_common` (the daemon is a
// separate crate and only holds the returned RAII guards + `WslcSdk`).
//
// COM affinity: unlike the one-shot path these do NOT call `CoInitializeEx` —
// the daemon worker thread joins the MTA for its whole lifetime before invoking
// any of them.

/// Long-lived container init command for daemon-owned containers. Unlike the
/// one-shot path (which bakes the caller's script as PID 1), the daemon needs an
/// init process that keeps the container alive across repeated `exec` calls.
/// `while true; do sleep 86400; done` is portable across busybox (`alpine`) and
/// coreutils (`mariner`/`fedora`/`python`) shells.
pub const KEEPALIVE_SCRIPT: &str = "while true; do sleep 86400; done";

/// Load the WSLc SDK and verify its runtime prerequisites, WITHOUT initialising
/// COM (the caller — the daemon worker thread — is already in the MTA).
///
/// # Safety
/// COM must already be initialised on the calling thread and the SDK DLL must be
/// resolvable. The returned [`WslcSdk`] holds raw function pointers; keep it
/// alive for the duration of all SDK use.
pub unsafe fn load_sdk_checked(logger: &mut Logger) -> Result<WslcSdk, WslcStepError> {
    let sdk = WslcSdk::load().map_err(|e| WslcError::Unavailable(e).into_step_error())?;

    let mut missing = WslcComponentFlags::WSLC_COMPONENT_FLAG_NONE;
    let hr = sdk.WslcGetMissingComponents(&mut missing);
    if hr != S_OK {
        return Err(sdk_step_error("WslcGetMissingComponents", hr, ""));
    }
    if missing.any_missing() {
        return Err(WslcError::Unavailable(sdk_init::prerequisite_error(missing)).into());
    }
    let _ = writeln!(logger, "[WSLC][daemon] Runtime check passed");
    Ok(sdk)
}

#[derive(Debug)]
pub struct SessionCreateFailure {
    pub response: WslcStepError,
    pub store_may_be_held: bool,
}

impl From<WslcStepError> for SessionCreateFailure {
    fn from(response: WslcStepError) -> Self {
        Self {
            response,
            store_may_be_held: false,
        }
    }
}

/// Whether a session maps Windows loopback to
/// [`HOST_LOOPBACK_NAME`](crate::wslc_gateway_policy::HOST_LOOPBACK_NAME),
/// which needs WSL 3.0.5 or later.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HostLoopback {
    Off,
    /// Falls back to a session without it on an older WSL.
    IfSupported,
    Required,
}

/// The policy needs a session that reaches Windows loopback, and this WSL
/// can't create one.
pub fn host_loopback_unsupported() -> WslcStepError {
    WslcError::Unavailable(
        "WSLc: network.ingress.hostLoopback 'allow' and a runtimeConfig.networkProxy \
         on Windows loopback need WSL 3.0.5 or later. Run `wsl --update`"
            .to_string(),
    )
    .into_step_error()
}

/// Create a session. Returns it and whether it reaches Windows loopback.
///
/// # Safety
/// `sdk` must hold valid function pointers and COM must be initialised on this
/// thread.
pub(crate) unsafe fn create_session(
    sdk: &WslcSdk,
    session_name: &str,
    storage_path: &str,
    sizing: SessionSizing,
    mut host_loopback: HostLoopback,
    logger: &mut Logger,
) -> Result<(WslcSessionGuard, bool), WslcStepError> {
    // The SDK reads these when the session is created.
    let name_wide: Vec<u16> = to_wide(session_name);
    let storage_wide: Vec<u16> = to_wide(storage_path);
    let host_loopback_name = CString::new(crate::wslc_gateway_policy::HOST_LOOPBACK_NAME)
        .expect("the host loopback name has no NUL");

    loop {
        let mut settings = std::mem::zeroed::<WslcSessionSettings>();
        let hr =
            sdk.WslcInitSessionSettings(name_wide.as_ptr(), storage_wide.as_ptr(), &mut settings);
        if hr != S_OK {
            return Err(sdk_step_error("WslcInitSessionSettings", hr, ""));
        }
        apply_session_sizing(sdk, &mut settings, sizing)?;
        let with_host_loopback = host_loopback != HostLoopback::Off;
        if with_host_loopback {
            let hr =
                sdk.WslcSetSessionSettingsHostLoopback(&mut settings, host_loopback_name.as_ptr());
            if hr != S_OK {
                return Err(sdk_step_error("WslcSetSessionSettingsHostLoopback", hr, ""));
            }
        }

        let mut session: WslcSession = ptr::null_mut();
        let mut err_msg = CoTaskMemPWSTR::null();
        let hr = sdk.WslcCreateSession(&mut settings, &mut session, err_msg.as_mut_ptr());
        if hr != S_OK {
            host_loopback = host_loopback_for_retry(hr, host_loopback, &err_msg.to_string_lossy())?;
            let _ = writeln!(
                logger,
                "[WSLC] This WSL can't map Windows loopback into session '{session_name}'; \
                 creating it without"
            );
            continue;
        }
        if with_host_loopback {
            let _ = writeln!(
                logger,
                "[WSLC] Session reaches Windows loopback as {}",
                crate::wslc_gateway_policy::HOST_LOOPBACK_NAME
            );
        }
        let guard = WslcSessionGuard::from_raw(
            session,
            sdk.terminate_session_fn(),
            sdk.release_session_fn(),
        );
        return Ok((guard, with_host_loopback));
    }
}

fn host_loopback_for_retry(
    hr: HRESULT,
    host_loopback: HostLoopback,
    sdk_msg: &str,
) -> Result<HostLoopback, WslcStepError> {
    match host_loopback {
        HostLoopback::IfSupported if hr == WSLC_E_RUNTIME_UPDATE_NEEDED => Ok(HostLoopback::Off),
        HostLoopback::Required if hr == WSLC_E_RUNTIME_UPDATE_NEEDED => {
            Err(host_loopback_unsupported()
                .with_api_failure(sdk_api_failure("WslcCreateSession", hr)))
        }
        _ => Err(sdk_step_error("WslcCreateSession", hr, sdk_msg)),
    }
}

/// Create a daemon session (a WSL2 utility VM) and confirm it can use its
/// store. Returns it and whether it reaches Windows loopback.
///
/// # Safety
/// `sdk` must hold valid function pointers and COM must be initialised on this
/// thread.
pub unsafe fn create_daemon_session(
    sdk: &WslcSdk,
    session_name: &str,
    storage_path: &str,
    sizing: SessionSizing,
    logger: &mut Logger,
) -> Result<(WslcSessionGuard, bool), SessionCreateFailure> {
    let started = Instant::now();
    let (guard, host_loopback) = create_session(
        sdk,
        session_name,
        storage_path,
        sizing,
        HostLoopback::IfSupported,
        logger,
    )?;
    let created_in = started.elapsed();

    // Timed separately from the create: a host that cannot supply the session
    // accepts it here in under a second and spends minutes failing in the
    // probe, so one figure would hide where the time went.
    let probed = Instant::now();
    let probe = validate_store_access(sdk, guard.as_raw(), storage_path);
    let probed_in = probed.elapsed();

    // Logged before the probe is allowed to fail, because the failing case is
    // the one whose timing matters.
    let _ = writeln!(
        logger,
        "[WSLC][daemon] Session '{session_name}' on store {storage_path}: create \
         {:.1}s, store probe {:.1}s, probe {}",
        created_in.as_secs_f32(),
        probed_in.as_secs_f32(),
        if probe.is_ok() { "ok" } else { "failed" }
    );

    if let Err(response) = probe {
        // Dropping the guard would ignore a failed terminate, and the caller
        // must know whether this VM may still hold the store.
        let store_may_be_held = match release_daemon_session(guard, session_name, logger) {
            Ok(()) => false,
            Err(release) => {
                let _ = writeln!(logger, "[WSLC][daemon] {}", release.error_message);
                true
            }
        };
        return Err(SessionCreateFailure {
            response,
            store_may_be_held,
        });
    }

    Ok((guard, host_loopback))
}

/// Apply a session's sizing and its boot deadline to `settings`.
///
/// The boot timeout is applied even when the caller asked for no sizing, since
/// `WslcCreateSession` is otherwise unbounded.
///
/// # Safety
/// `sdk` must hold valid function pointers and `settings` must be initialised.
unsafe fn apply_session_sizing(
    sdk: &WslcSdk,
    settings: &mut WslcSessionSettings,
    sizing: SessionSizing,
) -> Result<(), WslcStepError> {
    check_sizing_against_host(sizing)?;

    if let Some(cpu) = sizing.cpu_count {
        let hr = sdk.WslcSetSessionSettingsCpuCount(settings, cpu);
        if hr != S_OK {
            return Err(sdk_step_error("WslcSetSessionSettingsCpuCount", hr, ""));
        }
    }

    if let Some(memory_mb) = sizing.memory_mb {
        let memory_mb = u32::try_from(memory_mb).map_err(|_| {
            WslcError::Rejected(format!(
                "memory_mb {memory_mb} exceeds the {} MB the WSLc SDK accepts",
                u32::MAX
            ))
            .into_step_error()
        })?;
        let hr = sdk.WslcSetSessionSettingsMemory(settings, memory_mb);
        if hr != S_OK {
            return Err(sdk_step_error("WslcSetSessionSettingsMemory", hr, ""));
        }
    }

    let hr = sdk.WslcSetSessionSettingsTimeout(settings, SESSION_BOOT_TIMEOUT_MS);
    if hr != S_OK {
        return Err(sdk_step_error("WslcSetSessionSettingsTimeout", hr, ""));
    }

    if sizing.gpu {
        let hr = sdk.WslcSetSessionSettingsFeatureFlags(
            settings,
            WslcSessionFeatureFlags::WSLC_SESSION_FEATURE_FLAG_ENABLE_GPU,
        );
        if hr != S_OK {
            return Err(sdk_step_error("WslcSetSessionSettingsFeatureFlags", hr, ""));
        }
    }

    Ok(())
}

/// Terminate and release a session, reporting a terminate the SDK refused.
///
/// A session whose VM did not stop still holds its image store, so reporting
/// success would hand back a store slot the next lease cannot open.
pub fn release_daemon_session(
    session: WslcSessionGuard,
    session_name: &str,
    logger: &mut Logger,
) -> Result<(), WslcStepError> {
    let hr = session.release_checked();
    if hr != S_OK {
        return Err(sdk_step_error(
            "WslcTerminateSession",
            hr,
            &format!(
                "the WSL2 utility VM for session '{session_name}' may still be running, so its \
                 image store cannot be reused yet"
            ),
        ));
    }

    let _ = writeln!(logger, "[WSLC][daemon] Session '{session_name}' released");
    Ok(())
}

/// Confirm a session just created can reach the store it was given.
///
/// A store's VHDX admits one live session, and the SDK does not report a
/// conflict at create time: `WslcCreateSession` against a held store returns a
/// healthy-looking handle, and the violation appears on first use as
/// `HRESULT 0x80070020`. Probing here turns that into a create failure, so a
/// caller never mints a sandbox id against a session that would die at an
/// arbitrary later phase.
///
/// # Safety
/// `sdk` must hold valid function pointers and `session` must be a live handle.
pub unsafe fn validate_store_access(
    sdk: &WslcSdk,
    session: WslcSession,
    storage_path: &str,
) -> Result<(), WslcStepError> {
    list_stored_images(sdk, session)
        .map(|_| ())
        .map_err(|hr| store_access_failure(hr, storage_path))
}

/// Render a failed store probe, telling a sharing violation apart from any
/// other reason the store could not be read.
fn store_access_failure(hr: HRESULT, storage_path: &str) -> WslcStepError {
    if hr == E_SHARING_VIOLATION {
        sdk_step_error_with_context(
            "WslcListSessionImages",
            "WSLc store unavailable",
            hr,
            &format!(
                "the image store at {storage_path} is already held by another live session. \
                 A running wxc-wslc-daemon.exe releases it after its idle timeout; a \
                 create-and-run execution releases it when the run ends; a slot being \
                 warmed by --setup-wslc releases it when the warm finishes"
            ),
        )
    } else {
        sdk_step_error_with_context(
            "WslcListSessionImages",
            "WslcListSessionImages failed",
            hr,
            &format!("could not read the image store at {storage_path}"),
        )
    }
}

/// One entry of a session's image store.
pub(crate) struct StoredImage {
    pub(crate) name: String,
    pub(crate) sha256: [u8; 32],
}

/// Read a session's image store, preserving the `HRESULT` so a caller can tell
/// a sharing violation from any other failure.
///
/// # Safety
/// `sdk` must hold valid function pointers and `session` must be a live handle.
pub(crate) unsafe fn list_stored_images(
    sdk: &WslcSdk,
    session: WslcSession,
) -> Result<Vec<StoredImage>, HRESULT> {
    let mut images: *mut WslcImageInfo = ptr::null_mut();
    let mut count: u32 = 0;
    let hr = sdk.WslcListSessionImages(session, &mut images, &mut count);
    if hr != S_OK {
        return Err(hr);
    }
    if images.is_null() {
        return Ok(Vec::new());
    }

    let mut stored = Vec::with_capacity(count as usize);
    for info in std::slice::from_raw_parts(images, count as usize) {
        // `info.name` is a fixed-size, possibly-unterminated C buffer; read up
        // to the first NUL, or the whole buffer if there is none.
        let bytes = std::slice::from_raw_parts(info.name.as_ptr().cast::<u8>(), info.name.len());
        let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
        if let Ok(name) = std::str::from_utf8(&bytes[..end]) {
            stored.push(StoredImage {
                name: name.to_string(),
                sha256: info.sha256,
            });
        }
    }
    windows::Win32::System::Com::CoTaskMemFree(Some(images as *const c_void));

    Ok(stored)
}

/// The flags a lifecycle container is created with.
///
/// GPU is set on the session *and* the container; a session sized for a GPU
/// whose containers lack the flag gets no passthrough and reports nothing.
/// Auto-remove stays one-shot-only, since a lifecycle sandbox outlives its runs.
fn container_flags(gpu: bool) -> WslcContainerFlags {
    if gpu {
        WslcContainerFlags::WSLC_CONTAINER_FLAG_ENABLE_GPU
    } else {
        WslcContainerFlags::WSLC_CONTAINER_FLAG_NONE
    }
}

/// Create a daemon-owned container with `keepalive` as its init process, so it
/// stays alive across repeated `exec` calls. The caller keeps `keepalive`
/// stationary until this returns (the SDK reads its buffers at
/// `WslcCreateContainer` time).
///
/// # Safety
/// `sdk` must hold valid function pointers and `session` must be a live handle.
#[allow(clippy::too_many_arguments)]
pub unsafe fn create_daemon_container(
    sdk: &WslcSdk,
    session: WslcSession,
    image: &str,
    mounts: &[VolumeMount],
    port_mappings: &[PortMapping],
    networking: ContainerNetworking,
    gpu: bool,
    keepalive: &mut ProcessSettings,
    logger: &mut Logger,
) -> Result<WslcContainerGuard, WslcStepError> {
    let mut container_settings = ContainerSettings::build(
        sdk,
        image,
        mounts,
        port_mappings,
        networking,
        container_flags(gpu),
        logger,
    )?;

    let hr =
        sdk.WslcSetContainerSettingsInitProcess(container_settings.raw_mut(), keepalive.raw_mut());
    if hr != S_OK {
        return Err(sdk_step_error(
            "WslcSetContainerSettingsInitProcess",
            hr,
            "",
        ));
    }

    let mut container: WslcContainer = ptr::null_mut();
    let mut err_msg = CoTaskMemPWSTR::null();
    let hr = sdk.WslcCreateContainer(
        session,
        container_settings.raw(),
        &mut container,
        err_msg.as_mut_ptr(),
    );
    if hr != S_OK {
        let msg = err_msg.to_string_lossy();
        return Err(sdk_step_error("WslcCreateContainer", hr, &msg));
    }
    let _ = writeln!(logger, "[WSLC][daemon] Container created");

    Ok(WslcContainerGuard::from_raw(
        container,
        sdk.release_container_fn(),
    ))
}

/// Boot a created daemon container. Uses `START_FLAG_NONE` (not `ATTACH`): the
/// keepalive init's stdio is never streamed — per-`exec` processes carry the
/// user-visible I/O.
///
/// # Safety
/// `sdk` must hold valid function pointers and `container` must be a live handle.
pub unsafe fn start_daemon_container(
    sdk: &WslcSdk,
    container: WslcContainer,
    logger: &mut Logger,
) -> Result<(), WslcStepError> {
    let mut err_msg = CoTaskMemPWSTR::null();
    let hr = sdk.WslcStartContainer(
        container,
        WslcContainerStartFlags::WSLC_CONTAINER_START_FLAG_NONE,
        err_msg.as_mut_ptr(),
    );
    if hr != S_OK {
        let msg = err_msg.to_string_lossy();
        return Err(sdk_step_error("WslcStartContainer", hr, &msg));
    }
    let _ = writeln!(logger, "[WSLC][daemon] Container started");
    Ok(())
}

/// Maximum delay before observing cancellation while waiting for process exit.
const EXEC_WAIT_POLL_INTERVAL: Duration = Duration::from_millis(100);

/// Bounded wait for the SDK exit callback to confirm termination and flush I/O.
const EXIT_CALLBACK_WAIT: Duration = Duration::from_secs(30);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExecInterruption {
    TimedOut,
    Cancelled,
}

impl ExecInterruption {
    fn get_interruption_word(self) -> &'static str {
        match self {
            Self::TimedOut => "timeout",
            Self::Cancelled => "cancellation",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExitWait {
    Signalled,
    Interrupted(ExecInterruption),
    NoEvent,
    Failed { wait_result: u32, last_error: u32 },
}

fn wait_slice(timeout: Option<Duration>, elapsed: Duration) -> Duration {
    timeout
        .map(|limit| limit.saturating_sub(elapsed))
        .unwrap_or(EXEC_WAIT_POLL_INTERVAL)
        .min(EXEC_WAIT_POLL_INTERVAL)
}

fn wait_slice_ms(timeout: Option<Duration>, elapsed: Duration) -> u32 {
    u32::try_from(wait_slice(timeout, elapsed).as_millis())
        .expect("poll interval is bounded to 100ms")
}

fn requested_interruption(
    cancelled: bool,
    timeout: Option<Duration>,
    elapsed: Duration,
) -> Option<ExecInterruption> {
    if cancelled {
        Some(ExecInterruption::Cancelled)
    } else if timeout.is_some_and(|limit| elapsed >= limit) {
        Some(ExecInterruption::TimedOut)
    } else {
        None
    }
}

/// Wait for process exit or a cancellation/timeout request.
///
/// # Safety
/// `exit_event` must be null or a valid waitable event handle for the duration
/// of this call.
unsafe fn wait_for_exit_event(
    exit_event: HANDLE,
    io_ctx: &IoContext,
    timeout: Option<Duration>,
    cancellation: &AtomicBool,
) -> ExitWait {
    let started = Instant::now();
    loop {
        if let Some(interruption) = requested_interruption(
            cancellation.load(Ordering::Acquire),
            timeout,
            started.elapsed(),
        ) {
            return ExitWait::Interrupted(interruption);
        }

        if exit_event.is_null() {
            if wait_for_exit_callback_slice(io_ctx, wait_slice(timeout, started.elapsed())) {
                return ExitWait::NoEvent;
            }
            continue;
        }

        let wait_result = unsafe {
            windows::Win32::System::Threading::WaitForSingleObject(
                windows::Win32::Foundation::HANDLE(exit_event),
                wait_slice_ms(timeout, started.elapsed()),
            )
        };
        if wait_result == windows::Win32::Foundation::WAIT_OBJECT_0 {
            return ExitWait::Signalled;
        }
        if wait_result != windows::Win32::Foundation::WAIT_TIMEOUT {
            let last_error = unsafe { windows::Win32::Foundation::GetLastError() };
            return ExitWait::Failed {
                wait_result: wait_result.0,
                last_error: last_error.0,
            };
        }
    }
}

fn wait_for_exit_callback_slice(io_ctx: &IoContext, wait: Duration) -> bool {
    let (lock, cvar) = &*io_ctx.exited;
    let mut exited = lock.lock().unwrap_or_else(|e| e.into_inner());
    if !*exited {
        let result = cvar
            .wait_timeout(exited, wait)
            .unwrap_or_else(|e| e.into_inner());
        exited = result.0;
    }
    *exited
}

fn wait_for_exit_callback(io_ctx: &IoContext) -> bool {
    wait_for_exit_callback_slice(io_ctx, EXIT_CALLBACK_WAIT)
}

/// Terminal state of a daemon container process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessCompletion {
    Confirmed(ExecTerminal),
    /// The process could not be positively confirmed dead. The owning
    /// container must be quarantined and never reused.
    TerminationUnconfirmed,
}

fn natural_exit_confirmed(exit_wait: ExitWait, callback_confirmed: bool) -> bool {
    matches!(exit_wait, ExitWait::Signalled)
        || (matches!(exit_wait, ExitWait::NoEvent) && callback_confirmed)
}

#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
const TEST_EXIT_CODE_FAILURE_SCRIPT: &str = "true # mxc-test-force-wslc-get-exit-code-failure";

#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
fn forced_exit_code_result(
    script_code: &str,
    natural_exit_confirmed: bool,
    result: HRESULT,
) -> HRESULT {
    if result == S_OK && natural_exit_confirmed && script_code == TEST_EXIT_CODE_FAILURE_SCRIPT {
        E_FAIL
    } else {
        result
    }
}

pub(crate) fn test_exit_code_result(
    script_code: &str,
    natural_exit_confirmed: bool,
    result: HRESULT,
) -> HRESULT {
    #[cfg(all(feature = "test-support", debug_assertions))]
    let result = forced_exit_code_result(script_code, natural_exit_confirmed, result);

    let _ = (script_code, natural_exit_confirmed);
    result
}

fn classify_completion(exit_wait: ExitWait, confirmed: bool, exit_code: i32) -> ProcessCompletion {
    if natural_exit_confirmed(exit_wait, confirmed) {
        return ProcessCompletion::Confirmed(ExecTerminal::Exited(exit_code));
    }

    match exit_wait {
        ExitWait::Interrupted(ExecInterruption::TimedOut) if confirmed => {
            ProcessCompletion::Confirmed(ExecTerminal::TimedOut)
        }
        ExitWait::Interrupted(ExecInterruption::Cancelled) if confirmed => {
            ProcessCompletion::Confirmed(ExecTerminal::Cancelled)
        }
        ExitWait::Interrupted(_) | ExitWait::Failed { .. } => {
            ProcessCompletion::TerminationUnconfirmed
        }
        ExitWait::NoEvent | ExitWait::Signalled => ProcessCompletion::TerminationUnconfirmed,
    }
}

fn unconfirmed_api_failure(
    completion: ProcessCompletion,
    kill_hr: HRESULT,
    exit_code_hr: HRESULT,
) -> Option<Box<ApiFailure>> {
    if completion != ProcessCompletion::TerminationUnconfirmed {
        return None;
    }
    [
        ("WslcSignalProcess", kill_hr),
        ("WslcGetProcessExitCode", exit_code_hr),
    ]
    .into_iter()
    .find(|&(_, hr)| hr != S_OK)
    .map(|(operation, hr)| Box::new(sdk_api_failure(operation, hr)))
}

/// Result of a daemon `exec`, including captured output retained by callbacks.
#[derive(Debug)]
pub struct ExecOutcome {
    pub completion: ProcessCompletion,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
    /// Specific post-process-creation failure that made termination
    /// unobservable. The daemon uses this context when quarantining.
    pub post_launch_error: Option<WslcStepError>,

    /// For an unconfirmed termination, the first SDK call that failed while
    /// stopping the process or reading its exit code.
    pub unconfirmed_api_failure: Option<Box<ApiFailure>>,

    /// The process's stdin, still open because its termination was not
    /// confirmed.
    pub held_stdin: Option<StdinHold>,
}

/// Run `script_code` (under `/bin/sh -c`) as a fresh process inside a started
/// daemon container and wait for it to complete. On timeout the *process* is
/// killed (SIGKILL) — NOT the container — so the keepalive init survives for
/// subsequent execs.
///
/// Without `stdin`, the process reads end-of-file immediately.
///
/// # Safety
/// `sdk` must hold valid function pointers and `container` must be a live,
/// started handle.
#[expect(
    clippy::too_many_arguments,
    reason = "thin FFI boundary mirrors the SDK process inputs at its single call site"
)]
pub unsafe fn exec_in_container(
    sdk: &WslcSdk,
    container: WslcContainer,
    script_code: &str,
    env: &[String],
    scope: EnvScope,
    working_directory: &str,
    timeout_ms: u32,
    cancellation: &AtomicBool,
    sink: Option<OutputSink>,
    stdin: Option<StdinConsumer>,
    logger: &mut Logger,
) -> Result<ExecOutcome, WslcStepError> {
    // `process_settings` owns every buffer the SDK reads at
    // `WslcCreateContainerProcess` time plus the I/O-capture context; it is held
    // as a stationary local until after the process exits below.
    let mut process_settings =
        ProcessSettings::build(sdk, script_code, env, scope, working_directory, sink)?;
    if stdin.is_some() {
        let hr = sdk.WslcSetProcessSettingsFlags(
            process_settings.raw_mut(),
            WslcProcessFlags::WSLC_PROCESS_FLAG_STDIN,
        );
        if hr != S_OK {
            return Err(sdk_step_error("WslcSetProcessSettingsFlags", hr, ""));
        }
    }

    let mut process: WslcProcess = ptr::null_mut();
    let mut err_msg = CoTaskMemPWSTR::null();
    let hr = sdk.WslcCreateContainerProcess(
        container,
        process_settings.raw_mut(),
        &mut process,
        err_msg.as_mut_ptr(),
    );
    if hr != S_OK {
        let msg = err_msg.to_string_lossy();
        return Err(sdk_step_error("WslcCreateContainerProcess", hr, &msg));
    }
    let process_guard = WslcProcessGuard::from_raw(process, sdk.release_process_fn());
    // The process now owns the SDK's IoContext reference; `exit_callback` will
    // reclaim it. Disarm the settings guard so it is not freed underneath the SDK.
    process_settings.mark_process_created();

    let mut stdin_guard = StdinHold::default();
    let forwards_stdin = stdin.is_some();
    if let Some(consumer) = stdin {
        match attach_stdin(sdk, process_guard.as_raw(), consumer) {
            Ok(close) => stdin_guard = StdinHold::new(close),
            Err(error) => {
                // A process holding a stdin nobody writes or closes would never
                // see end-of-file, so it is killed rather than left to run.
                let kill_hr =
                    sdk.WslcSignalProcess(process_guard.as_raw(), WslcSignal::WSLC_SIGNAL_SIGKILL);
                if wait_for_exit_callback(process_settings.io_ctx()) {
                    return Err(error);
                }
                let completion = ProcessCompletion::TerminationUnconfirmed;
                return Ok(ExecOutcome {
                    completion,
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                    post_launch_error: Some(error),
                    unconfirmed_api_failure: unconfirmed_api_failure(completion, kill_hr, S_OK),
                    held_stdin: None,
                });
            }
        }
    }

    let mut exit_event: HANDLE = ptr::null_mut();
    let hr = sdk.WslcGetProcessExitEvent(process_guard.as_raw(), &mut exit_event);
    if hr != S_OK {
        return Ok(ExecOutcome {
            completion: ProcessCompletion::TerminationUnconfirmed,
            stdout: Vec::new(),
            stderr: Vec::new(),
            post_launch_error: Some(sdk_step_error("WslcGetProcessExitEvent", hr, "")),
            unconfirmed_api_failure: None,
            held_stdin: Some(stdin_guard),
        });
    }

    let timeout = (timeout_ms > 0).then(|| Duration::from_millis(u64::from(timeout_ms)));
    let exit_wait =
        wait_for_exit_event(exit_event, process_settings.io_ctx(), timeout, cancellation);

    if let ExitWait::Failed {
        wait_result,
        last_error,
    } = exit_wait
    {
        let _ = writeln!(
            logger,
            "[WSLC][daemon] Warning: waiting on the exec exit event failed: \
             WaitForSingleObject returned 0x{wait_result:08X} \
             (GetLastError 0x{last_error:08X}); container state is unknown"
        );
    }

    let interruption = match exit_wait {
        ExitWait::Interrupted(interruption) => Some(interruption),
        _ => None,
    };
    let mut kill_hr = S_OK;
    if let Some(interruption) = interruption {
        if forwards_stdin {
            stdin_guard.freeze();

            // Signalling the process closes its stdin even when the signal is
            // not delivered, which would let it act on input that was cut short.
            let _ = writeln!(
                logger,
                "[WSLC][daemon] exec {} — not signalling a process that reads forwarded \
                 stdin; it is stopped with its container",
                interruption.get_interruption_word()
            );
        } else {
            let _ = writeln!(
                logger,
                "[WSLC][daemon] exec {} — killing process",
                interruption.get_interruption_word()
            );

            // Kill only this process; the keepalive init keeps the container up.
            kill_hr =
                sdk.WslcSignalProcess(process_guard.as_raw(), WslcSignal::WSLC_SIGNAL_SIGKILL);
            if kill_hr != S_OK {
                let _ = writeln!(
                    logger,
                    "[WSLC][daemon] Warning: WslcSignalProcess(SIGKILL) failed (hr=0x{:08X}); \
                     process may still be running",
                    kill_hr as u32
                );
            }
        }
    }

    // Wait for the exit callback — the only proof the process is actually gone
    // and that all captured I/O has been flushed.
    let mut confirmed = wait_for_exit_callback(process_settings.io_ctx());
    if interruption.is_some() && !confirmed {
        // The SIGKILL was only a request and plainly has not landed yet; give
        // the callback one more bounded chance before declaring the outcome
        // unconfirmed.
        confirmed = wait_for_exit_callback(process_settings.io_ctx());
        if !confirmed {
            let _ = writeln!(
                logger,
                "[WSLC][daemon] Warning: exit callback did not fire after SIGKILL; \
                 process may still be running"
            );
        }
    }

    let mut exit_code: i32 = -1;
    let natural_exit_confirmed = natural_exit_confirmed(exit_wait, confirmed);
    let exit_code_hr = test_exit_code_result(
        script_code,
        natural_exit_confirmed,
        sdk.WslcGetProcessExitCode(process_guard.as_raw(), &mut exit_code),
    );
    if exit_code_hr != S_OK {
        if natural_exit_confirmed {
            return Err(sdk_step_error("WslcGetProcessExitCode", exit_code_hr, ""));
        }
        let _ = writeln!(
            logger,
            "[WSLC][daemon] Warning: WslcGetProcessExitCode failed while termination was \
             unconfirmed (hr=0x{:08X})",
            exit_code_hr as u32
        );
    }

    let stdout = process_settings
        .io_ctx()
        .stdout
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone();
    let stderr = process_settings
        .io_ctx()
        .stderr
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .clone();

    // Resolve the reported outcome from positive evidence only.
    let completion = classify_completion(exit_wait, confirmed, exit_code);
    match completion {
        ProcessCompletion::Confirmed(ExecTerminal::TimedOut) => {
            let _ = writeln!(
                logger,
                "[WSLC][daemon] Process killed after {}",
                ExecInterruption::TimedOut.get_interruption_word()
            );
        }
        ProcessCompletion::Confirmed(ExecTerminal::Cancelled) => {
            let _ = writeln!(
                logger,
                "[WSLC][daemon] Process killed after {}",
                ExecInterruption::Cancelled.get_interruption_word()
            );
        }
        ProcessCompletion::Confirmed(ExecTerminal::Exited(exit_code)) => {
            let _ = writeln!(
                logger,
                "[WSLC][daemon] Process exited with code {}",
                exit_code
            );
        }
        ProcessCompletion::TerminationUnconfirmed if matches!(exit_wait, ExitWait::NoEvent) => {
            let _ = writeln!(
                logger,
                "[WSLC][daemon] Warning: exec never reported an exit (no exit event, no exit \
                 callback); container state is unknown"
            );
        }
        ProcessCompletion::TerminationUnconfirmed => {}
    }

    // A process that may still be running keeps its stdin open, so it cannot
    // take a cut-short input as complete before it is stopped.
    let held_stdin = match completion {
        ProcessCompletion::Confirmed(_) => {
            drop(stdin_guard);
            None
        }
        ProcessCompletion::TerminationUnconfirmed => Some(stdin_guard),
    };

    Ok(ExecOutcome {
        completion,
        stdout,
        stderr,
        post_launch_error: None,
        unconfirmed_api_failure: unconfirmed_api_failure(completion, kill_hr, exit_code_hr),
        held_stdin,
    })
}

/// A process's stdin, closed when this is dropped.
#[derive(Default)]
pub struct StdinHold(Mutex<Option<Box<dyn StdinControl>>>);

impl StdinHold {
    fn new(control: Box<dyn StdinControl>) -> Self {
        Self(Mutex::new(Some(control)))
    }

    fn freeze(&self) {
        if let Some(control) = self
            .0
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .as_ref()
        {
            control.freeze();
        }
    }
}

impl Drop for StdinHold {
    fn drop(&mut self) {
        let control = self
            .0
            .get_mut()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .take();
        if let Some(control) = control {
            control.close();
        }
    }
}

impl std::fmt::Debug for StdinHold {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("StdinHold")
    }
}

/// Hand `process`'s stdin write end to `consumer`.
///
/// # Safety
/// `sdk` must hold valid function pointers and `process` must be a live handle
/// created with `WSLC_PROCESS_FLAG_STDIN`.
unsafe fn attach_stdin(
    sdk: &WslcSdk,
    process: WslcProcess,
    consumer: StdinConsumer,
) -> Result<Box<dyn StdinControl>, WslcStepError> {
    use std::os::windows::io::FromRawHandle;

    let mut handle: HANDLE = ptr::null_mut();
    let hr = sdk.WslcGetProcessIOHandle(
        process,
        WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDIN,
        &mut handle,
    );
    if hr != S_OK || handle.is_null() {
        return Err(sdk_step_error_with_context(
            "WslcGetProcessIOHandle",
            "WslcGetProcessIOHandle(stdin) failed",
            hr,
            "",
        ));
    }

    // SAFETY: the SDK transfers ownership of the returned handle to the caller.
    let stdin = std::fs::File::from_raw_handle(handle);
    consumer(stdin).map_err(|error| {
        WslcError::Runtime(format!("could not start forwarding stdin: {error}")).into_step_error()
    })
}

/// Stop a running daemon container (SIGTERM), keeping it created for a later
/// `start`.
///
/// # Safety
/// `sdk` must hold valid function pointers and `container` must be a live handle.
pub unsafe fn stop_daemon_container(
    sdk: &WslcSdk,
    container: WslcContainer,
    logger: &mut Logger,
) -> Result<(), WslcStepError> {
    let mut err_msg = CoTaskMemPWSTR::null();
    let hr = sdk.WslcStopContainer(
        container,
        WslcSignal::WSLC_SIGNAL_SIGTERM,
        10,
        err_msg.as_mut_ptr(),
    );
    if hr != S_OK {
        let msg = err_msg.to_string_lossy();
        return Err(sdk_step_error("WslcStopContainer", hr, &msg));
    }
    let _ = writeln!(logger, "[WSLC][daemon] Container stopped");
    Ok(())
}

/// Delete a daemon container (forcefully).
///
/// # Safety
/// `sdk` must hold valid function pointers and `container` must be a live handle.
pub unsafe fn delete_daemon_container(
    sdk: &WslcSdk,
    container: WslcContainer,
    logger: &mut Logger,
) -> Result<(), WslcStepError> {
    let mut err_msg = CoTaskMemPWSTR::null();
    let hr = sdk.WslcDeleteContainer(
        container,
        WslcDeleteContainerFlags::WSLC_DELETE_CONTAINER_FLAG_FORCE,
        err_msg.as_mut_ptr(),
    );
    if hr != S_OK {
        let msg = err_msg.to_string_lossy();
        return Err(sdk_step_error("WslcDeleteContainer", hr, &msg));
    }
    let _ = writeln!(logger, "[WSLC][daemon] Container deleted");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::FailurePhase;

    #[test]
    fn test_exit_code_failure_requires_the_exact_successful_natural_exit() {
        let access_denied = 0x8007_0005_u32 as HRESULT;
        assert_eq!(
            forced_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, S_OK),
            E_FAIL
        );
        assert_eq!(
            forced_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, access_denied),
            access_denied
        );
        assert_eq!(
            forced_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, false, S_OK),
            S_OK
        );
        assert_eq!(
            forced_exit_code_result(
                "true # mxc-test-force-wslc-get-exit-code-failure ",
                true,
                S_OK
            ),
            S_OK
        );
    }

    #[cfg(all(feature = "test-support", debug_assertions))]
    #[test]
    fn the_exit_code_failure_marker_fails_the_call_with_test_support() {
        assert_eq!(
            test_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, S_OK),
            E_FAIL
        );
    }

    #[cfg(not(all(feature = "test-support", debug_assertions)))]
    #[test]
    fn the_exit_code_failure_marker_is_inert_without_test_support() {
        assert_eq!(
            test_exit_code_result(TEST_EXIT_CODE_FAILURE_SCRIPT, true, S_OK),
            S_OK
        );
    }

    /// A modest machine: 16 GB and 8 logical processors.
    const TEST_HOST: HostCapacity = HostCapacity {
        total_memory_mb: 16 * 1024,
        logical_cpus: 8,
    };

    #[test]
    fn port_mappings_bind_windows_ipv4_loopback() {
        let mapping = PortMapping {
            windows_port: 8080,
            container_port: 80,
            protocol: "tcp".to_string(),
        };
        let sdk = sdk_port_mappings(&[mapping]);
        // SAFETY: points at the 'static WINDOWS_LOOPBACK.
        let address = unsafe { &*sdk[0].windowsAddress };
        assert_eq!(address.ss_family, 2);
        assert_eq!(address.__ss_pad1, [0, 0, 127, 0, 0, 1]);
    }

    #[test]
    fn a_processor_count_the_host_cannot_supply_is_refused() {
        let refused = sizing_fits_host(
            SessionSizing {
                cpu_count: Some(TEST_HOST.logical_cpus + 1),
                ..SessionSizing::default()
            },
            TEST_HOST,
        )
        .expect_err("more processors than the host has must be refused");

        assert_eq!(refused.failure_phase, FailurePhase::Rejected);
        assert!(
            refused.error_message.contains('9') && refused.error_message.contains('8'),
            "the refusal must name both what was asked and what the host has: {}",
            refused.error_message
        );
    }

    #[test]
    fn a_processor_count_the_host_can_supply_is_allowed() {
        for cpus in [1, TEST_HOST.logical_cpus] {
            assert!(
                sizing_fits_host(
                    SessionSizing {
                        cpu_count: Some(cpus),
                        ..SessionSizing::default()
                    },
                    TEST_HOST,
                )
                .is_ok(),
                "{cpus} processors is within the host's {}",
                TEST_HOST.logical_cpus
            );
        }
    }

    /// `memory_mb` is a ceiling the host backs on demand, not a reservation,
    /// so a request past installed memory is legitimate.
    #[test]
    fn memory_past_installed_is_allowed_because_it_is_a_ceiling() {
        assert!(
            sizing_fits_host(
                SessionSizing {
                    memory_mb: Some(TEST_HOST.total_memory_mb * 8),
                    ..SessionSizing::default()
                },
                TEST_HOST,
            )
            .is_ok(),
            "memory_mb is a ceiling the host backs on demand, not a reservation"
        );
    }

    /// The SDK documents `0` as "reset to the default" for both figures, so it
    /// is a sentinel rather than a size and must not be measured against the
    /// host.
    #[test]
    fn zero_is_a_default_sentinel_rather_than_a_size() {
        assert!(sizing_fits_host(
            SessionSizing {
                cpu_count: Some(0),
                memory_mb: Some(0),
                gpu: false,
            },
            TEST_HOST,
        )
        .is_ok());
    }

    /// A request that names no sizing takes the host defaults and has nothing
    /// to check.
    #[test]
    fn absent_sizing_is_allowed() {
        assert!(sizing_fits_host(SessionSizing::default(), TEST_HOST).is_ok());
    }

    /// A session sized for a GPU whose containers lack the flag gets no
    /// passthrough and reports nothing, so the two halves must agree.
    #[test]
    fn a_gpu_session_creates_gpu_containers() {
        assert_eq!(
            container_flags(true),
            WslcContainerFlags::WSLC_CONTAINER_FLAG_ENABLE_GPU
        );
        assert_eq!(
            container_flags(false),
            WslcContainerFlags::WSLC_CONTAINER_FLAG_NONE
        );
    }

    #[test]
    fn a_held_store_is_reported_as_held_rather_than_as_a_failed_call() {
        let resp = store_access_failure(E_SHARING_VIOLATION, r"C:\slots\slot-0");

        assert!(
            resp.error_message
                .contains("already held by another live session"),
            "a sharing violation is the one store failure a caller can wait out: {}",
            resp.error_message
        );
        assert!(resp.error_message.contains(r"C:\slots\slot-0"));
        assert!(resp.error_message.contains("idle timeout"));
        assert!(
            resp.error_message.contains("--setup-wslc"),
            "warming holds a slot's store too, and that holder clears on its own: {}",
            resp.error_message
        );
        assert!(resp.error_message.contains("80070020"));
    }

    #[test]
    fn any_other_store_failure_keeps_the_call_that_produced_it() {
        let resp = store_access_failure(-2147467259, r"C:\slots\slot-0");

        assert!(
            resp.error_message.contains("WslcListSessionImages failed"),
            "an unrecognised failure must not be attributed to another holder: {}",
            resp.error_message
        );
        assert!(!resp.error_message.contains("already held"));
        assert!(resp.error_message.contains(r"C:\slots\slot-0"));
    }

    #[test]
    fn a_failed_sdk_call_keeps_its_message_and_names_the_call() {
        let error = sdk_step_error(
            "WslcStartContainer",
            0x8007_2740_u32 as HRESULT,
            "Only one usage of each socket address is normally permitted.",
        );

        assert_eq!(
            error.error_message,
            "WslcStartContainer failed: Only one usage of each socket address is normally \
             permitted. (HRESULT 0x80072740)"
        );
        let failure = error.api_failure.as_deref().expect("api failure");
        assert_eq!(failure.operation, "WslcStartContainer");
        assert_eq!(failure.native_code.as_deref(), Some("0x80072740"));
    }

    #[test]
    fn a_store_failure_is_attributed_to_bring_up() {
        assert_eq!(
            store_access_failure(E_SHARING_VIOLATION, "store").failure_phase,
            FailurePhase::LaunchFailed,
            "a held store frees up on its own, so this must not read as a rejection"
        );
    }

    #[test]
    fn cstr_bytes_nul_terminates_a_plain_value() {
        let bytes = cstr_bytes("command", "echo hi").expect("plain value is a valid C string");
        assert_eq!(bytes, b"echo hi\0");
    }

    #[test]
    fn cstr_bytes_accepts_empty() {
        let bytes = cstr_bytes("working_directory", "").expect("empty value is a valid C string");
        assert_eq!(bytes, b"\0");
    }

    #[test]
    fn cstr_bytes_rejects_interior_nul() {
        let err = cstr_bytes("command", "echo\0rm -rf /")
            .expect_err("an interior NUL must be rejected, not silently truncated");
        let msg = format!("{:?}", err);
        assert!(msg.contains("command"), "error names the field: {msg}");
        assert!(
            msg.contains("interior NUL"),
            "error explains the cause: {msg}"
        );
    }

    #[test]
    fn wait_slice_is_bounded_by_poll_interval_and_deadline() {
        assert_eq!(wait_slice(None, Duration::ZERO), Duration::from_millis(100));
        assert_eq!(
            wait_slice(Some(Duration::from_millis(250)), Duration::from_millis(225),),
            Duration::from_millis(25)
        );
        assert_eq!(wait_slice_ms(None, Duration::ZERO), 100);
        assert_eq!(
            wait_slice_ms(Some(Duration::from_millis(250)), Duration::from_millis(25)),
            100
        );
        assert_eq!(
            wait_slice_ms(Some(Duration::from_millis(250)), Duration::from_millis(225)),
            25
        );
        assert_eq!(
            wait_slice_ms(Some(Duration::from_millis(250)), Duration::from_millis(250)),
            0
        );
    }

    #[test]
    fn cancellation_takes_precedence_over_an_expired_timeout() {
        assert_eq!(
            requested_interruption(
                true,
                Some(Duration::from_millis(10)),
                Duration::from_millis(10),
            ),
            Some(ExecInterruption::Cancelled)
        );
    }

    #[test]
    fn timeout_requires_a_nonzero_deadline_to_expire() {
        assert_eq!(
            requested_interruption(false, None, Duration::from_secs(1)),
            None
        );
        assert_eq!(
            requested_interruption(
                false,
                Some(Duration::from_millis(10)),
                Duration::from_millis(9),
            ),
            None
        );
        assert_eq!(
            requested_interruption(
                false,
                Some(Duration::from_millis(10)),
                Duration::from_millis(10),
            ),
            Some(ExecInterruption::TimedOut)
        );
    }

    #[test]
    fn completion_classification_requires_positive_exit_evidence() {
        assert_eq!(
            classify_completion(ExitWait::Signalled, false, 7),
            ProcessCompletion::Confirmed(ExecTerminal::Exited(7))
        );
        assert_eq!(
            classify_completion(ExitWait::NoEvent, true, 8),
            ProcessCompletion::Confirmed(ExecTerminal::Exited(8))
        );
        assert_eq!(
            classify_completion(ExitWait::Interrupted(ExecInterruption::TimedOut), true, -1,),
            ProcessCompletion::Confirmed(ExecTerminal::TimedOut)
        );
        assert_eq!(
            classify_completion(ExitWait::Interrupted(ExecInterruption::Cancelled), true, -1,),
            ProcessCompletion::Confirmed(ExecTerminal::Cancelled)
        );
        assert_eq!(
            classify_completion(
                ExitWait::Interrupted(ExecInterruption::Cancelled),
                false,
                -1,
            ),
            ProcessCompletion::TerminationUnconfirmed
        );
        assert_eq!(
            classify_completion(
                ExitWait::Failed {
                    wait_result: 1,
                    last_error: 2,
                },
                true,
                0,
            ),
            ProcessCompletion::TerminationUnconfirmed
        );
        assert_eq!(
            classify_completion(ExitWait::NoEvent, false, -1),
            ProcessCompletion::TerminationUnconfirmed
        );
    }

    #[test]
    fn an_unconfirmed_run_names_its_first_failed_kill_or_exit_code_call() {
        let unconfirmed = ProcessCompletion::TerminationUnconfirmed;
        let kill_failed = 0x8007_001f_u32 as HRESULT;
        let kill_failure = ApiFailure::new("WslcSignalProcess").with_native_code("0x8007001f");
        let exit_code_failure =
            ApiFailure::new("WslcGetProcessExitCode").with_native_code("0x80004005");

        assert_eq!(
            unconfirmed_api_failure(unconfirmed, kill_failed, E_FAIL).as_deref(),
            Some(&kill_failure)
        );
        assert_eq!(
            unconfirmed_api_failure(unconfirmed, S_OK, E_FAIL).as_deref(),
            Some(&exit_code_failure)
        );
        assert_eq!(unconfirmed_api_failure(unconfirmed, S_OK, S_OK), None);
        assert_eq!(
            unconfirmed_api_failure(
                ProcessCompletion::Confirmed(ExecTerminal::TimedOut),
                kill_failed,
                E_FAIL,
            ),
            None,
            "a confirmed timeout must stay a timeout"
        );
    }

    /// A streaming caller reads its bytes from the sink, so a second capped
    /// copy would double the daemon's per-exec output memory.
    #[test]
    fn a_streaming_callback_captures_nothing() {
        let streamed = Arc::new(Mutex::new(Vec::new()));
        let seen = Arc::clone(&streamed);
        let io_ctx = Arc::new(IoContext {
            stdout: Arc::new(Mutex::new(Vec::new())),
            stderr: Arc::new(Mutex::new(Vec::new())),
            exited: Arc::new((Mutex::new(false), Condvar::new())),
            sink: Some(Box::new(move |kind, bytes| {
                seen.lock().unwrap().push((kind, bytes.to_vec()));
            })),
            capture: Capture::Head,
        });

        let payload = b"streamed-not-captured";
        let raw = Arc::into_raw(Arc::clone(&io_ctx));
        // SAFETY: `raw` is a live `Arc<IoContext>` pointer and `payload` is
        // valid for its full length, matching what the SDK passes.
        unsafe {
            io_callback(
                WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDOUT,
                payload.as_ptr(),
                payload.len() as u32,
                raw as *mut c_void,
            );
            drop(Arc::from_raw(raw));
        }

        assert_eq!(
            streamed.lock().unwrap().as_slice(),
            &[(OutStream::Stdout, payload.to_vec())]
        );
        assert!(
            io_ctx.stdout.lock().unwrap().is_empty(),
            "a streamed chunk must not also be captured"
        );
    }

    #[test]
    fn null_exit_event_still_observes_cancellation() {
        let io_ctx = IoContext {
            stdout: Arc::new(Mutex::new(Vec::new())),
            stderr: Arc::new(Mutex::new(Vec::new())),
            exited: Arc::new((Mutex::new(false), Condvar::new())),
            sink: None,
            capture: Capture::Head,
        };
        let cancellation = AtomicBool::new(true);

        let result = unsafe { wait_for_exit_event(ptr::null_mut(), &io_ctx, None, &cancellation) };

        assert_eq!(result, ExitWait::Interrupted(ExecInterruption::Cancelled));
    }

    #[test]
    fn null_exit_event_uses_callback_as_natural_exit_evidence() {
        let io_ctx = IoContext {
            stdout: Arc::new(Mutex::new(Vec::new())),
            stderr: Arc::new(Mutex::new(Vec::new())),
            exited: Arc::new((Mutex::new(true), Condvar::new())),
            sink: None,
            capture: Capture::Head,
        };
        let cancellation = AtomicBool::new(false);

        let result = unsafe { wait_for_exit_event(ptr::null_mut(), &io_ctx, None, &cancellation) };

        assert_eq!(result, ExitWait::NoEvent);
    }

    #[test]
    fn an_older_wsl_gets_one_retry_without_host_loopback_only_when_it_is_optional() {
        let old_wsl = WSLC_E_RUNTIME_UPDATE_NEEDED;
        let refused = sdk_api_failure("WslcCreateSession", old_wsl);

        let retry = host_loopback_for_retry(old_wsl, HostLoopback::IfSupported, "")
            .expect("an optional host loopback is dropped for an older WSL");
        assert_eq!(retry, HostLoopback::Off);
        let refused_again = host_loopback_for_retry(old_wsl, retry, "")
            .expect_err("the retry without host loopback is the last attempt");
        assert_eq!(refused_again.failure_phase, FailurePhase::LaunchFailed);
        assert_eq!(refused_again.api_failure.as_deref(), Some(&refused));

        let required = host_loopback_for_retry(old_wsl, HostLoopback::Required, "")
            .expect_err("a required host loopback is never dropped");
        assert_eq!(required.failure_phase, FailurePhase::BackendUnavailable);
        assert!(
            required.error_message.contains("wsl --update"),
            "{}",
            required.error_message
        );
        assert_eq!(required.api_failure.as_deref(), Some(&refused));
    }

    #[test]
    fn other_session_failures_are_returned_whatever_host_loopback_asks() {
        for host_loopback in [
            HostLoopback::Off,
            HostLoopback::IfSupported,
            HostLoopback::Required,
        ] {
            let error = host_loopback_for_retry(E_FAIL, host_loopback, "no VM")
                .expect_err("only an older WSL is retried");
            assert_eq!(
                error.failure_phase,
                FailurePhase::LaunchFailed,
                "{host_loopback:?}"
            );
            assert!(
                error.error_message.contains("no VM"),
                "{}",
                error.error_message
            );
            assert_eq!(
                error.api_failure.as_deref(),
                Some(&sdk_api_failure("WslcCreateSession", E_FAIL))
            );
        }
    }

    #[test]
    fn sustained_output_keeps_only_the_newest_whole_lines_under_a_tail_capture() {
        let io_ctx = Arc::new(IoContext {
            stdout: Arc::new(Mutex::new(Vec::new())),
            stderr: Arc::new(Mutex::new(Vec::new())),
            exited: Arc::new((Mutex::new(false), Condvar::new())),
            sink: None,
            capture: Capture::Tail(64),
        });
        let raw = Arc::into_raw(Arc::clone(&io_ctx));

        // SAFETY: `raw` is a live `Arc<IoContext>` pointer and each line is
        // valid for its full length.
        unsafe {
            for i in 0..1000 {
                let line = format!("DENY  request {i}\n");
                io_callback(
                    WslcProcessIOHandle::WSLC_PROCESS_IO_HANDLE_STDOUT,
                    line.as_ptr(),
                    line.len() as u32,
                    raw as *mut c_void,
                );
                let kept = io_ctx.stdout.lock().unwrap().len();
                assert!(kept <= 64, "{kept} bytes kept after line {i}");
            }
            drop(Arc::from_raw(raw));
        }

        let kept = String::from_utf8(io_ctx.stdout.lock().unwrap().clone()).unwrap();
        assert!(kept.starts_with("DENY  "), "{kept:?}");
        assert!(kept.ends_with("DENY  request 999\n"), "{kept:?}");
    }

    #[test]
    fn a_tail_capture_keeps_the_newest_bytes_of_a_line_longer_than_its_limit() {
        let mut buf = Vec::new();
        Capture::Tail(4).append(&mut buf, b"abcdefgh");
        assert_eq!(buf, b"efgh");
    }
}