native-ipc 0.6.0

One safe API for least-authority native shared memory: sealed memfd on Linux, Mach memory entries on macOS, exact-rights sections on Windows
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
//! Windows unnamed-section mappings, pipe identity, and Job containment.

use std::ffi::{OsStr, OsString};
use std::fmt;
use std::mem::{size_of, zeroed};
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::path::Path;
use std::ptr::NonNull;
use std::time::{Duration, Instant};

use native_ipc_core::layout::{RegionSetLayout, ValidatedRegionLayout, ValidationExpectations};
use native_ipc_core::mapping::{
    BindingError, ReadOnlyMapping, ReaderRegion, SoleWriterMapping, WriterRegion,
};
use windows_sys::Win32::Foundation::{
    CloseHandle, DuplicateHandle, ERROR_BROKEN_PIPE, ERROR_INSUFFICIENT_BUFFER, ERROR_NO_DATA,
    ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, ERROR_PIPE_LISTENING, ERROR_PIPE_NOT_CONNECTED,
    GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
    WAIT_TIMEOUT,
};
use windows_sys::Win32::Security::Cryptography::{
    BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom,
};
use windows_sys::Win32::Security::{
    ACCESS_ALLOWED_ACE, ACL, ACL_REVISION, AddAccessAllowedAceEx, GetLengthSid,
    GetTokenInformation, InitializeAcl, InitializeSecurityDescriptor, IsValidSid,
    SECURITY_ATTRIBUTES, SECURITY_DESCRIPTOR, SetSecurityDescriptorDacl, TOKEN_GROUPS, TOKEN_QUERY,
    TokenLogonSid,
};
use windows_sys::Win32::Storage::FileSystem::{
    BY_HANDLE_FILE_INFORMATION, CreateFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL,
    FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OPEN_REPARSE_POINT,
    FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_READ, GetFileInformationByHandle,
    OPEN_EXISTING, PIPE_ACCESS_DUPLEX, ReadFile, WriteFile,
};
use windows_sys::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
    SetInformationJobObject,
};
use windows_sys::Win32::System::Memory::{
    CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE,
    MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, MEM_RESERVE_PLACEHOLDER, MEMORY_MAPPED_VIEW_ADDRESS,
    MapViewOfFile, MapViewOfFile3, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, SEC_COMMIT,
    UnmapViewOfFile, UnmapViewOfFile2, VirtualAlloc2, VirtualFree,
};
use windows_sys::Win32::System::Pipes::{
    ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, GetNamedPipeClientProcessId,
    GetNamedPipeServerProcessId, PIPE_NOWAIT, PIPE_READMODE_MESSAGE, PIPE_REJECT_REMOTE_CLIENTS,
    PIPE_TYPE_MESSAGE, SetNamedPipeHandleState,
};
use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO};
use windows_sys::Win32::System::Threading::{
    CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, CreateProcessW, GetCurrentProcess,
    GetCurrentProcessId, GetExitCodeProcess, OpenProcessToken, PROCESS_INFORMATION,
    QueryFullProcessImageNameW, ResumeThread, STARTUPINFOW, TerminateProcess, WaitForSingleObject,
};

use crate::protocol::{
    CONTROL_FRAME_LEN, ManifestEntry, NativeRegionSpec, PeerAccess, TransferManifest,
    TransferProvenance, mint_channel_id,
};
use crate::session::AbsoluteDeadline;

/// Windows section, bootstrap, lifecycle, or binding failure.
#[derive(Debug)]
pub enum WindowsError {
    /// Win32 API failed with a captured `GetLastError` value.
    Os {
        /// Bounded Win32 operation name.
        operation: &'static str,
        /// Captured `GetLastError` value.
        code: u32,
    },
    /// Mapping size is zero or cannot be page-rounded.
    InvalidSize(usize),
    /// Named-pipe peer PID differs from the held expected process.
    WrongPeer,
    /// Received or duplicated handle is invalid for this process.
    InvalidHandle,
    /// Quiescent layout validation failed.
    Layout(native_ipc_core::layout::LayoutError),
    /// Audited core binding failed.
    Binding(BindingError),
    /// Bootstrap environment or authenticated handshake was malformed.
    InvalidBootstrap,
    /// The bootstrap designation is absent: this process was not spawned as
    /// a receiver, so no peer exists and nothing was negotiated.
    MissingBootstrap,
    /// A sole-writer capability was already duplicated from this preparation.
    CapabilityAlreadyTransferred,
    /// A bounded bootstrap or lifecycle operation reached its deadline.
    TimedOut(&'static str),
    /// The exact helper exited unsuccessfully.
    ChildExit(u32),
    /// A pending value came from another channel or transfer transaction.
    ForeignPending,
}

impl fmt::Display for WindowsError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "Windows transport failed: {self:?}")
    }
}
impl std::error::Error for WindowsError {}
impl From<native_ipc_core::layout::LayoutError> for WindowsError {
    fn from(value: native_ipc_core::layout::LayoutError) -> Self {
        Self::Layout(value)
    }
}
impl From<BindingError> for WindowsError {
    fn from(value: BindingError) -> Self {
        Self::Binding(value)
    }
}

/// Generates a nonzero 256-bit bootstrap nonce from the system RNG.
pub fn session_nonce() -> Result<[u8; 32], WindowsError> {
    let mut nonce = [0_u8; 32];
    // SAFETY: output buffer is valid; null algorithm selects system-preferred RNG.
    let status = unsafe {
        BCryptGenRandom(
            std::ptr::null_mut(),
            nonce.as_mut_ptr(),
            nonce.len() as u32,
            BCRYPT_USE_SYSTEM_PREFERRED_RNG,
        )
    };
    if status < 0 || nonce == [0; 32] {
        Err(last_os("BCryptGenRandom"))
    } else {
        Ok(nonce)
    }
}

/// Verifies the connected client of a private named-pipe server instance.
///
/// # Safety
///
/// `pipe` must be a live connected named-pipe server handle owned by the caller.
pub unsafe fn authenticate_pipe_client(
    pipe: HANDLE,
    expected_pid: u32,
) -> Result<(), WindowsError> {
    let mut actual = 0;
    // SAFETY: caller supplies a live pipe and output pointer is valid.
    if unsafe { GetNamedPipeClientProcessId(pipe, &mut actual) } == 0 {
        return Err(last_os("GetNamedPipeClientProcessId"));
    }
    if actual == expected_pid {
        Ok(())
    } else {
        Err(WindowsError::WrongPeer)
    }
}

/// Verifies the connected server of a private named-pipe client instance.
///
/// # Safety
///
/// `pipe` must be a live connected named-pipe client handle owned by the caller.
pub unsafe fn authenticate_pipe_server(
    pipe: HANDLE,
    expected_pid: u32,
) -> Result<(), WindowsError> {
    let mut actual = 0;
    // SAFETY: caller supplies a live pipe and output pointer is valid.
    if unsafe { GetNamedPipeServerProcessId(pipe, &mut actual) } == 0 {
        return Err(last_os("GetNamedPipeServerProcessId"));
    }
    if actual == expected_pid {
        Ok(())
    } else {
        Err(WindowsError::WrongPeer)
    }
}

/// Quiescent unnamed paging-file section and exclusive initialization view.
pub struct QuiescentRegion {
    section: OwnedHandle,
    view: View,
    logical_len: usize,
}

impl QuiescentRegion {
    /// Allocates a page-rounded unnamed, non-executable section.
    pub fn new(logical_len: usize) -> Result<Self, WindowsError> {
        let len = page_align(logical_len)?;
        let size = len as u64;
        // SAFETY: paging-file sentinel, null security/name, and checked size are valid.
        let section = unsafe {
            CreateFileMappingW(
                INVALID_HANDLE_VALUE,
                std::ptr::null(),
                PAGE_READWRITE | SEC_COMMIT,
                (size >> 32) as u32,
                size as u32,
                std::ptr::null(),
            )
        };
        let section = OwnedHandle::new(section)?;
        let view = View::map(section.0, len, FILE_MAP_WRITE)?;
        // SAFETY: newly created unnamed section view is exclusive and writable.
        unsafe { std::slice::from_raw_parts_mut(view.base.as_ptr(), len) }.fill(0);
        Ok(Self {
            section,
            view,
            logical_len,
        })
    }
    /// Exact page-rounded capability size.
    pub const fn len(&self) -> usize {
        self.view.len
    }
    /// Returns whether the capability is empty (always false for valid values).
    pub const fn is_empty(&self) -> bool {
        false
    }
    /// Requested logical layout length.
    pub const fn logical_len(&self) -> usize {
        self.logical_len
    }
    /// Full quiescent initialization range.
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY: no duplicated handle or second view exists in this typestate.
        unsafe { std::slice::from_raw_parts(self.view.base.as_ptr(), self.view.len) }
    }
    /// Mutable full quiescent initialization range.
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        // SAFETY: `&mut self` and typestate provide exclusivity.
        unsafe { std::slice::from_raw_parts_mut(self.view.base.as_ptr(), self.view.len) }
    }

    /// Validates a future local-writer region before attenuated duplication.
    pub fn prepare_local_writer(
        self,
        native: NativeRegionSpec,
        expected: ValidationExpectations,
        topology: RegionSetLayout,
    ) -> Result<PreparedLocalWriter, WindowsError> {
        // SAFETY: section is quiescent and complete capability range is borrowed.
        let layout =
            unsafe { ValidatedRegionLayout::validate(self.as_bytes(), expected, &topology) }?;
        let len = self.view.len;
        if native.mapped_len != len as u64 {
            return Err(WindowsError::InvalidBootstrap);
        }
        let entry = ManifestEntry::from_native(native, PeerAccess::ReadOnly);
        Ok(PreparedLocalWriter {
            section: self.section,
            runtime: WriterRegion::new(WindowsWriterMapping { view: self.view }, layout, topology)
                .map_err(|(_, error)| error)?,
            entry,
            len,
            reader_duplicated: false,
        })
    }

    /// Validates a future remote-writer region before remapping local read-only.
    pub fn prepare_remote_writer(
        self,
        native: NativeRegionSpec,
        expected: ValidationExpectations,
        topology: RegionSetLayout,
    ) -> Result<PreparedRemoteWriter, WindowsError> {
        // SAFETY: section is quiescent and complete capability range is borrowed.
        let layout =
            unsafe { ValidatedRegionLayout::validate(self.as_bytes(), expected, &topology) }?;
        let len = self.view.len;
        drop(self.view);
        let view = View::map(self.section.0, len, FILE_MAP_READ)?;
        if native.mapped_len != len as u64 {
            return Err(WindowsError::InvalidBootstrap);
        }
        let entry = ManifestEntry::from_native(native, PeerAccess::SoleWriter);
        Ok(PreparedRemoteWriter {
            section: self.section,
            runtime: ReaderRegion::new(WindowsReaderMapping { view }, layout, topology)
                .map_err(|(_, error)| error)?,
            entry,
            len,
            writer_duplicated: false,
        })
    }
}

/// Target-process handle value produced by exact-rights duplication.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RemoteHandle(pub usize);

/// Local unique writer awaiting a read-only peer handle and READY barrier.
pub struct PreparedLocalWriter {
    section: OwnedHandle,
    runtime: WriterRegion<WindowsWriterMapping>,
    entry: ManifestEntry,
    len: usize,
    reader_duplicated: bool,
}
impl PreparedLocalWriter {
    /// Duplicates exactly `FILE_MAP_READ` into a held authenticated target process.
    ///
    /// # Safety
    ///
    /// `target_process` must be the held live process authenticated by the pipe.
    unsafe fn duplicate_reader_to(
        &mut self,
        target_process: HANDLE,
    ) -> Result<RemoteHandle, WindowsError> {
        if self.reader_duplicated {
            return Err(WindowsError::CapabilityAlreadyTransferred);
        }
        let handle = duplicate_to(self.section.0, target_process, FILE_MAP_READ)?;
        self.reader_duplicated = true;
        Ok(handle)
    }
}

/// Local read-only view awaiting the sole remote-writer handle and READY barrier.
pub struct PreparedRemoteWriter {
    section: OwnedHandle,
    runtime: ReaderRegion<WindowsReaderMapping>,
    entry: ManifestEntry,
    len: usize,
    writer_duplicated: bool,
}
impl PreparedRemoteWriter {
    /// Duplicates exactly one `FILE_MAP_WRITE` handle into a held authenticated target.
    ///
    /// # Safety
    ///
    /// `target_process` must be the held live process authenticated by the pipe.
    unsafe fn duplicate_writer_to(
        &mut self,
        target_process: HANDLE,
    ) -> Result<RemoteHandle, WindowsError> {
        if self.writer_duplicated {
            return Err(WindowsError::CapabilityAlreadyTransferred);
        }
        let handle = duplicate_to(self.section.0, target_process, FILE_MAP_WRITE)?;
        self.writer_duplicated = true;
        Ok(handle)
    }
}

/// Validated imported reader withheld until the creator acknowledges READY.
pub struct PendingImportedReader {
    runtime: ReaderRegion<WindowsReaderMapping>,
    entry: ManifestEntry,
    provenance: TransferProvenance,
}

/// Validated imported writer withheld until the creator acknowledges READY.
pub struct PendingImportedWriter {
    runtime: WriterRegion<WindowsWriterMapping>,
    entry: ManifestEntry,
    provenance: TransferProvenance,
}

/// Kill-on-last-handle Job Object used to contain an exact spawned helper tree.
pub struct ChildJob(OwnedHandle);
impl ChildJob {
    /// Creates an unnamed non-inheritable kill-on-close job.
    pub fn new() -> Result<Self, WindowsError> {
        // SAFETY: null security/name create an unnamed non-inheritable job.
        let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        let handle = OwnedHandle::new(handle)?;
        let mut information: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { zeroed() };
        information.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        // SAFETY: buffer type/size match the requested information class.
        if unsafe {
            SetInformationJobObject(
                handle.0,
                JobObjectExtendedLimitInformation,
                (&information as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
                size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
            )
        } == 0
        {
            return Err(last_os("SetInformationJobObject"));
        }
        Ok(Self(handle))
    }
    /// Assigns a still-suspended exact child before any untrusted code runs.
    ///
    /// # Safety
    ///
    /// `process` must be the live suspended child handle returned by CreateProcess.
    pub unsafe fn assign_suspended(&self, process: HANDLE) -> Result<(), WindowsError> {
        // SAFETY: caller proves process handle/lifecycle; job handle is live.
        if unsafe { AssignProcessToJobObject(self.0.0, process) } == 0 {
            Err(last_os("AssignProcessToJobObject"))
        } else {
            Ok(())
        }
    }
}

const PIPE_ENV: &str = "NATIVE_IPC_WINDOWS_PIPE";
const NONCE_ENV: &str = "NATIVE_IPC_WINDOWS_NONCE";
const PARENT_ENV: &str = "NATIVE_IPC_PARENT_PID";
const PUBLIC_BOOTSTRAP_ENV: &str = "NATIVE_IPC_VNEXT_PUBLIC_BOOTSTRAP";
const BOOTSTRAP_MAGIC: [u8; 8] = *b"NIPCWIN1";
const AUTH_MAGIC: [u8; 8] = *b"NIPCAUT1";
const READY_MAGIC: [u8; 8] = *b"NIPCRDY1";
const COMMIT_MAGIC: [u8; 8] = *b"NIPCCMT1";
const CAPABILITY_MAGIC: [u8; 8] = *b"NIPCCAP1";
const MAX_VNEXT_RECORD_BYTES: usize = 64 * 1024;
#[cfg(not(test))]
const WAIT_MS: u32 = 10_000;
#[cfg(test)]
const WAIT_MS: u32 = 1_000;

#[repr(C)]
#[derive(Clone, Copy)]
struct BootstrapFrame {
    magic: [u8; 8],
    nonce: [u8; 32],
    parent_pid: u32,
    child_pid: u32,
}

const CAPABILITY_FRAME_LEN: usize = 40 + CONTROL_FRAME_LEN;
const SECURITY_DESCRIPTOR_REVISION: u32 = 1;

struct PipeSecurity {
    _descriptor: Box<SECURITY_DESCRIPTOR>,
    _acl: Vec<usize>,
    attributes: SECURITY_ATTRIBUTES,
}

impl PipeSecurity {
    fn for_current_logon() -> Result<Self, WindowsError> {
        let mut token = core::ptr::null_mut();
        // SAFETY: current-process pseudo handle is valid and output is writable.
        if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
            return Err(last_os("OpenProcessToken"));
        }
        let token = OwnedHandle::new(token)?;
        let mut token_bytes = 0_u32;
        // SAFETY: null output asks for the exact TokenLogonSid byte count.
        if unsafe {
            GetTokenInformation(
                token.0,
                TokenLogonSid,
                core::ptr::null_mut(),
                0,
                &mut token_bytes,
            )
        } != 0
            || unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER
            || token_bytes < size_of::<TOKEN_GROUPS>() as u32
        {
            return Err(last_os("GetTokenInformation(size)"));
        }
        let word = size_of::<usize>();
        let mut token_buffer = vec![0_usize; (token_bytes as usize).div_ceil(word)];
        // SAFETY: the aligned buffer has the exact byte capacity requested above.
        if unsafe {
            GetTokenInformation(
                token.0,
                TokenLogonSid,
                token_buffer.as_mut_ptr().cast(),
                token_bytes,
                &mut token_bytes,
            )
        } == 0
        {
            return Err(last_os("GetTokenInformation(TokenLogonSid)"));
        }
        let groups = unsafe { &*token_buffer.as_ptr().cast::<TOKEN_GROUPS>() };
        if groups.GroupCount != 1 || groups.Groups[0].Sid.is_null() {
            return Err(WindowsError::InvalidBootstrap);
        }
        let sid = groups.Groups[0].Sid;
        if unsafe { IsValidSid(sid) } == 0 {
            return Err(WindowsError::InvalidBootstrap);
        }
        let sid_len = unsafe { GetLengthSid(sid) } as usize;
        let acl_len = size_of::<ACL>()
            .checked_add(size_of::<ACCESS_ALLOWED_ACE>())
            .and_then(|value| value.checked_add(sid_len))
            .and_then(|value| value.checked_sub(size_of::<u32>()))
            .ok_or(WindowsError::InvalidBootstrap)?;
        let mut acl = vec![0_usize; acl_len.div_ceil(word)];
        let acl_ptr = acl.as_mut_ptr().cast::<ACL>();
        let acl_bytes = u32::try_from(acl_len).map_err(|_| WindowsError::InvalidBootstrap)?;
        // SAFETY: the aligned ACL allocation remains owned by PipeSecurity.
        if unsafe { InitializeAcl(acl_ptr, acl_bytes, ACL_REVISION) } == 0 {
            return Err(last_os("InitializeAcl"));
        }
        // SAFETY: AddAccessAllowedAceEx copies the validated logon SID into the ACL.
        if unsafe {
            AddAccessAllowedAceEx(
                acl_ptr,
                ACL_REVISION,
                0,
                FILE_GENERIC_READ | FILE_GENERIC_WRITE,
                sid,
            )
        } == 0
        {
            return Err(last_os("AddAccessAllowedAceEx"));
        }
        let mut descriptor = Box::new(SECURITY_DESCRIPTOR::default());
        // SAFETY: descriptor storage is writable and remains pinned by Box allocation.
        if unsafe {
            InitializeSecurityDescriptor(
                (&raw mut *descriptor).cast(),
                SECURITY_DESCRIPTOR_REVISION,
            )
        } == 0
        {
            return Err(last_os("InitializeSecurityDescriptor"));
        }
        // SAFETY: descriptor and ACL remain live together in PipeSecurity.
        if unsafe { SetSecurityDescriptorDacl((&raw mut *descriptor).cast(), 1, acl_ptr, 0) } == 0 {
            return Err(last_os("SetSecurityDescriptorDacl"));
        }
        let attributes = SECURITY_ATTRIBUTES {
            nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: (&raw mut *descriptor).cast(),
            bInheritHandle: 0,
        };
        Ok(Self {
            _descriptor: descriptor,
            _acl: acl,
            attributes,
        })
    }
}

fn encode_capability_frame(
    reader: RemoteHandle,
    reader_len: usize,
    writer: RemoteHandle,
    writer_len: usize,
    transcript: &[u8; CONTROL_FRAME_LEN],
) -> Result<[u8; CAPABILITY_FRAME_LEN], WindowsError> {
    let mut frame = [0_u8; CAPABILITY_FRAME_LEN];
    frame[..8].copy_from_slice(&CAPABILITY_MAGIC);
    frame[8..16].copy_from_slice(
        &u64::try_from(reader.0)
            .map_err(|_| WindowsError::InvalidBootstrap)?
            .to_le_bytes(),
    );
    frame[16..24].copy_from_slice(
        &u64::try_from(writer.0)
            .map_err(|_| WindowsError::InvalidBootstrap)?
            .to_le_bytes(),
    );
    frame[24..32].copy_from_slice(
        &u64::try_from(reader_len)
            .map_err(|_| WindowsError::InvalidBootstrap)?
            .to_le_bytes(),
    );
    frame[32..40].copy_from_slice(
        &u64::try_from(writer_len)
            .map_err(|_| WindowsError::InvalidBootstrap)?
            .to_le_bytes(),
    );
    frame[40..].copy_from_slice(transcript);
    Ok(frame)
}

/// Parent-owned exact helper, private pipe, process handle, and kill-on-close job.
pub struct ChildSession {
    pipe: OwnedHandle,
    process: OwnedHandle,
    _job: ChildJob,
    pid: u32,
    nonce: [u8; 32],
    reaped: bool,
    next_transfer_id: u64,
    pending_manifest: Option<TransferManifest>,
    _executable: Option<HeldExecutable>,
}

pub(crate) struct ChildSpawnFailure {
    pub(crate) error: WindowsError,
    pub(crate) child_was_created: bool,
}

impl ChildSpawnFailure {
    fn before_child(error: WindowsError) -> Self {
        Self {
            error,
            child_was_created: false,
        }
    }

    fn after_child(error: WindowsError) -> Self {
        Self {
            error,
            child_was_created: true,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ExecutableIdentity {
    volume_serial: u32,
    file_index: u64,
    file_size: u64,
    last_write: u64,
}

struct HeldExecutable {
    _handle: OwnedHandle,
    identity: ExecutableIdentity,
}

impl HeldExecutable {
    fn open(path: &Path) -> Result<Self, WindowsError> {
        let path = wide_null(path.as_os_str());
        // SAFETY: the absolute terminated path is live. Sharing read only
        // prevents later writers or replacement while the identity is held.
        let handle = unsafe {
            CreateFileW(
                path.as_ptr(),
                GENERIC_READ,
                FILE_SHARE_READ,
                std::ptr::null(),
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
                std::ptr::null_mut(),
            )
        };
        let handle = OwnedHandle::new(handle)?;
        let identity = executable_identity(handle.0)?;
        if identity.file_size == 0 {
            return Err(WindowsError::InvalidBootstrap);
        }
        Ok(Self {
            _handle: handle,
            identity,
        })
    }

    fn verify_process_image(&self, process: HANDLE) -> Result<(), WindowsError> {
        let mut path = vec![0_u16; 32_768];
        let mut length = path.len() as u32;
        // SAFETY: held exact process and writable UTF-16 output are valid.
        if unsafe { QueryFullProcessImageNameW(process, 0, path.as_mut_ptr(), &mut length) } == 0 {
            return Err(last_os("QueryFullProcessImageNameW"));
        }
        let length = usize::try_from(length).map_err(|_| WindowsError::InvalidBootstrap)?;
        if length == 0 || length > path.len() {
            return Err(WindowsError::InvalidBootstrap);
        }
        let image = OsString::from_wide(&path[..length]);
        let observed = Self::open(Path::new(&image))?;
        if observed.identity == self.identity {
            Ok(())
        } else {
            Err(WindowsError::WrongPeer)
        }
    }
}

fn executable_identity(handle: HANDLE) -> Result<ExecutableIdentity, WindowsError> {
    let mut information: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
    // SAFETY: held file handle and exact output structure are valid.
    if unsafe { GetFileInformationByHandle(handle, &mut information) } == 0 {
        return Err(last_os("GetFileInformationByHandle"));
    }
    if information.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0
    {
        return Err(WindowsError::InvalidBootstrap);
    }
    Ok(ExecutableIdentity {
        volume_serial: information.dwVolumeSerialNumber,
        file_index: (u64::from(information.nFileIndexHigh) << 32)
            | u64::from(information.nFileIndexLow),
        file_size: (u64::from(information.nFileSizeHigh) << 32)
            | u64::from(information.nFileSizeLow),
        last_write: (u64::from(information.ftLastWriteTime.dwHighDateTime) << 32)
            | u64::from(information.ftLastWriteTime.dwLowDateTime),
    })
}

impl ChildSession {
    /// Creates a one-instance local pipe and launches the helper suspended.
    pub fn spawn(path: &Path, arguments: &[OsString]) -> Result<Self, WindowsError> {
        let deadline = AbsoluteDeadline::after(Duration::from_millis(WAIT_MS.into()))
            .map_err(|_| WindowsError::InvalidBootstrap)?;
        let arguments = std::iter::once(path.as_os_str().to_owned())
            .chain(arguments.iter().cloned())
            .collect::<Vec<_>>();
        Self::spawn_until(path, &arguments, &[], deadline).map_err(|failure| failure.error)
    }

    /// Creates a public-session child under one caller-owned absolute deadline
    /// and an explicit environment that starts empty.
    pub(crate) fn spawn_until(
        path: &Path,
        arguments: &[OsString],
        environment: &[(OsString, OsString)],
        deadline: AbsoluteDeadline,
    ) -> Result<Self, ChildSpawnFailure> {
        if deadline.is_expired() || arguments.is_empty() || !path.is_absolute() {
            return Err(ChildSpawnFailure::before_child(WindowsError::TimedOut(
                "public spawn",
            )));
        }
        let executable = HeldExecutable::open(path).map_err(ChildSpawnFailure::before_child)?;
        let nonce = session_nonce().map_err(ChildSpawnFailure::before_child)?;
        let name = format!(r"\\.\pipe\native-ipc-{}", hex(&nonce));
        let pipe_name = wide_null(OsStr::new(&name));
        let pipe_security =
            PipeSecurity::for_current_logon().map_err(ChildSpawnFailure::before_child)?;
        // SAFETY: name and explicit logon-SID-only security attributes remain live.
        let pipe = unsafe {
            CreateNamedPipeW(
                pipe_name.as_ptr(),
                PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
                PIPE_TYPE_MESSAGE
                    | PIPE_READMODE_MESSAGE
                    | PIPE_NOWAIT
                    | PIPE_REJECT_REMOTE_CLIENTS,
                1,
                MAX_VNEXT_RECORD_BYTES as u32,
                MAX_VNEXT_RECORD_BYTES as u32,
                WAIT_MS,
                &raw const pipe_security.attributes,
            )
        };
        let pipe = OwnedHandle::new(pipe).map_err(ChildSpawnFailure::before_child)?;
        let job = ChildJob::new().map_err(ChildSpawnFailure::before_child)?;

        let application = wide_null(path.as_os_str());
        let mut command = command_line_exact(arguments);
        let parent_pid = unsafe { GetCurrentProcessId() };
        let environment = environment_block_exact(
            environment,
            &[
                (PIPE_ENV, name),
                (NONCE_ENV, hex(&nonce)),
                (PARENT_ENV, parent_pid.to_string()),
                (PUBLIC_BOOTSTRAP_ENV, "1".to_owned()),
            ],
        )
        .map_err(ChildSpawnFailure::before_child)?;
        let mut startup: STARTUPINFOW = unsafe { zeroed() };
        startup.cb = size_of::<STARTUPINFOW>() as u32;
        let mut information: PROCESS_INFORMATION = unsafe { zeroed() };
        // SAFETY: all UTF-16 buffers and output structures remain live; no handles inherit.
        if unsafe {
            CreateProcessW(
                application.as_ptr(),
                command.as_mut_ptr(),
                std::ptr::null(),
                std::ptr::null(),
                0,
                CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT,
                environment.as_ptr().cast(),
                std::ptr::null(),
                &startup,
                &mut information,
            )
        } == 0
        {
            return Err(ChildSpawnFailure::before_child(last_os("CreateProcessW")));
        }
        let process =
            OwnedHandle::new(information.hProcess).map_err(ChildSpawnFailure::after_child)?;
        let thread =
            OwnedHandle::new(information.hThread).map_err(ChildSpawnFailure::after_child)?;
        // SAFETY: CreateProcessW returned this exact child still suspended.
        if let Err(error) = unsafe { job.assign_suspended(process.0) } {
            // SAFETY: exact held child is still suspended.
            let _ = unsafe { TerminateProcess(process.0, 127) };
            return Err(ChildSpawnFailure::after_child(error));
        }
        if let Err(error) = executable.verify_process_image(process.0) {
            // SAFETY: exact held child is still suspended and contained by the Job.
            let _ = unsafe { TerminateProcess(process.0, 127) };
            return Err(ChildSpawnFailure::after_child(error));
        }
        // SAFETY: thread is the exact suspended primary thread.
        if unsafe { ResumeThread(thread.0) } == u32::MAX {
            let error = last_os("ResumeThread");
            let _ = unsafe { TerminateProcess(process.0, 127) };
            return Err(ChildSpawnFailure::after_child(error));
        }
        drop(thread);
        let bootstrap_deadline = Instant::now() + deadline.remaining();
        connect_authenticated_pipe(
            pipe.0,
            process.0,
            information.dwProcessId,
            bootstrap_deadline,
        )
        .map_err(ChildSpawnFailure::after_child)?;
        let hello = BootstrapFrame {
            magic: BOOTSTRAP_MAGIC,
            nonce,
            parent_pid,
            child_pid: information.dwProcessId,
        };
        write_frame_until(pipe.0, &hello, bootstrap_deadline)
            .map_err(ChildSpawnFailure::after_child)?;
        let ready =
            read_frame_until(pipe.0, bootstrap_deadline).map_err(ChildSpawnFailure::after_child)?;
        if ready.magic != AUTH_MAGIC
            || ready.nonce != nonce
            || ready.parent_pid != parent_pid
            || ready.child_pid != information.dwProcessId
        {
            let _ = unsafe { TerminateProcess(process.0, 127) };
            return Err(ChildSpawnFailure::after_child(
                WindowsError::InvalidBootstrap,
            ));
        }
        Ok(Self {
            pipe,
            process,
            _job: job,
            pid: information.dwProcessId,
            nonce,
            reaped: false,
            next_transfer_id: 1,
            pending_manifest: None,
            _executable: Some(executable),
        })
    }

    /// Exact live process handle used only for attenuated handle duplication.
    pub const fn process_handle(&self) -> HANDLE {
        self.process.0
    }
    /// Kernel-created child process ID authenticated on the private pipe.
    pub const fn pid(&self) -> u32 {
        self.pid
    }
    pub(crate) const fn vnext_nonce(&self) -> [u8; 32] {
        self.nonce
    }
    /// Sends the two exact-rights handle values and their complete mapped lengths.
    fn send_capabilities(
        &mut self,
        reader_handle: RemoteHandle,
        reader: &PreparedLocalWriter,
        writer_handle: RemoteHandle,
        remote_writer: &PreparedRemoteWriter,
    ) -> Result<(), WindowsError> {
        if self.pending_manifest.is_some() {
            return Err(WindowsError::InvalidBootstrap);
        }
        let manifest = TransferManifest::new(
            self.nonce,
            unsafe { GetCurrentProcessId() },
            self.pid,
            self.next_transfer_id,
            vec![reader.entry, remote_writer.entry],
        )
        .ok_or(WindowsError::InvalidBootstrap)?;
        let frame = encode_capability_frame(
            reader_handle,
            reader.len,
            writer_handle,
            remote_writer.len,
            &manifest.encode(CAPABILITY_MAGIC),
        )?;
        write_pod(self.pipe.0, &frame)?;
        self.pending_manifest = Some(manifest);
        Ok(())
    }
    /// Consumes prepared mappings after authenticated READY and sends COMMIT.
    ///
    /// This method owns capability duplication, the remote-handle cleanup
    /// ledger, exact manifest transfer, READY validation, and COMMIT. It returns
    /// `(local_writer, local_reader)` only after successful COMMIT.
    ///
    /// # Errors
    ///
    /// Returns an error for duplication, pipe, transcript, timeout, or process
    /// failures. Ambiguous failure terminates and reaps the exact held child.
    pub fn commit_transfers(
        &mut self,
        writer: PreparedLocalWriter,
        reader: PreparedRemoteWriter,
    ) -> Result<
        (
            WriterRegion<WindowsWriterMapping>,
            ReaderRegion<WindowsReaderMapping>,
        ),
        WindowsError,
    > {
        let result = self.commit_transfers_inner(writer, reader);
        if result.is_err() {
            self.abort_child();
        }
        result
    }

    fn commit_transfers_inner(
        &mut self,
        mut writer: PreparedLocalWriter,
        mut reader: PreparedRemoteWriter,
    ) -> Result<
        (
            WriterRegion<WindowsWriterMapping>,
            ReaderRegion<WindowsReaderMapping>,
        ),
        WindowsError,
    > {
        // SAFETY: this session owns the exact authenticated live child handle.
        let reader_handle = unsafe { writer.duplicate_reader_to(self.process.0)? };
        // SAFETY: same held child; the preparation enforces one writer duplicate.
        let writer_handle = unsafe { reader.duplicate_writer_to(self.process.0)? };
        self.send_capabilities(reader_handle, &writer, writer_handle, &reader)?;
        let manifest = self
            .pending_manifest
            .as_ref()
            .ok_or(WindowsError::InvalidBootstrap)?;
        let ready: [u8; CONTROL_FRAME_LEN] = read_pod(self.pipe.0)?;
        if !manifest.matches_frame(READY_MAGIC, &ready) {
            return Err(WindowsError::InvalidBootstrap);
        }
        write_pod(self.pipe.0, &manifest.encode(COMMIT_MAGIC))?;
        drop(writer.section);
        drop(reader.section);
        self.pending_manifest = None;
        self.next_transfer_id = self
            .next_transfer_id
            .checked_add(1)
            .ok_or(WindowsError::InvalidBootstrap)?;
        Ok((writer.runtime, reader.runtime))
    }

    fn abort_child(&mut self) -> Option<u32> {
        if !self.reaped {
            // SAFETY: this session owns the exact authenticated child handle.
            let _ = unsafe { TerminateProcess(self.process.0, 127) };
            // SAFETY: same held process; bounded wait completes cleanup.
            let waited = unsafe { WaitForSingleObject(self.process.0, WAIT_MS) };
            self.reaped = true;
            if waited != WAIT_OBJECT_0 {
                return None;
            }
        }
        let mut code = 0;
        // SAFETY: the exact held process has exited and the output is writable.
        if unsafe { GetExitCodeProcess(self.process.0, &mut code) } == 0 {
            return None;
        }
        Some(code)
    }
    /// Waits for a normal helper exit after protocol completion.
    pub fn wait(mut self) -> Result<(), WindowsError> {
        // SAFETY: process is held live for this session.
        match unsafe { WaitForSingleObject(self.process.0, WAIT_MS) } {
            WAIT_OBJECT_0 => {
                let mut code = 0;
                // SAFETY: held process is signaled and output pointer is valid.
                if unsafe { GetExitCodeProcess(self.process.0, &mut code) } == 0 {
                    return Err(last_os("GetExitCodeProcess"));
                }
                if code != 0 {
                    return Err(WindowsError::ChildExit(code));
                }
            }
            WAIT_TIMEOUT => return Err(WindowsError::TimedOut("helper exit")),
            _ => return Err(last_os("WaitForSingleObject")),
        }
        self.reaped = true;
        Ok(())
    }
}

impl Drop for ChildSession {
    fn drop(&mut self) {
        if !self.reaped {
            // SAFETY: exact held child; job close remains the backstop for descendants.
            let _ = unsafe { TerminateProcess(self.process.0, 127) };
            let _ = unsafe { WaitForSingleObject(self.process.0, WAIT_MS) };
        }
    }
}

/// Connects a spawned helper from its authenticated bootstrap environment.
pub fn connect_spawned_helper() -> Result<ChildChannel, WindowsError> {
    let deadline = AbsoluteDeadline::after(Duration::from_millis(WAIT_MS.into()))
        .map_err(|_| WindowsError::InvalidBootstrap)?;
    connect_spawned_helper_until(deadline)
}

// SAFETY: the owner uniquely retains its process, pipe, and Job handles. Moving
// the complete non-Sync owner between threads does not duplicate authority.
unsafe impl Send for ChildSession {}

/// Connects the public receiver bootstrap under the caller's absolute deadline.
pub(crate) fn connect_spawned_helper_until(
    deadline: AbsoluteDeadline,
) -> Result<ChildChannel, WindowsError> {
    let name = std::env::var_os(PIPE_ENV).ok_or(WindowsError::MissingBootstrap)?;
    let nonce =
        parse_nonce(&std::env::var(NONCE_ENV).map_err(|_| WindowsError::MissingBootstrap)?)?;
    let parent_pid = std::env::var(PARENT_ENV)
        .map_err(|_| WindowsError::MissingBootstrap)?
        .parse::<u32>()
        .map_err(|_| WindowsError::InvalidBootstrap)?;
    if std::env::var(PUBLIC_BOOTSTRAP_ENV).as_deref() != Ok("1") {
        return Err(match std::env::var(PUBLIC_BOOTSTRAP_ENV) {
            Err(_) => WindowsError::MissingBootstrap,
            Ok(_) => WindowsError::InvalidBootstrap,
        });
    }
    // SAFETY: bootstrap environment is process-local startup state. Scrubbing
    // it before application-controlled process creation prevents delegation.
    unsafe {
        std::env::remove_var(PIPE_ENV);
        std::env::remove_var(NONCE_ENV);
        std::env::remove_var(PARENT_ENV);
        std::env::remove_var(PUBLIC_BOOTSTRAP_ENV);
    }
    let name = wide_null(&name);
    let bootstrap_deadline = Instant::now() + deadline.remaining();
    let pipe = open_pipe_until(name.as_ptr(), bootstrap_deadline)?;
    let mode = PIPE_READMODE_MESSAGE | PIPE_NOWAIT;
    // SAFETY: connected client pipe and mode pointer are valid.
    if unsafe { SetNamedPipeHandleState(pipe.0, &mode, std::ptr::null(), std::ptr::null()) } == 0 {
        return Err(last_os("SetNamedPipeHandleState"));
    }
    // SAFETY: connected pipe client and exact expected parent from spawn environment.
    unsafe { authenticate_pipe_server(pipe.0, parent_pid)? };
    let hello = read_frame_until(pipe.0, bootstrap_deadline)?;
    let child_pid = unsafe { GetCurrentProcessId() };
    if hello.magic != BOOTSTRAP_MAGIC
        || hello.nonce != nonce
        || hello.parent_pid != parent_pid
        || hello.child_pid != child_pid
    {
        return Err(WindowsError::InvalidBootstrap);
    }
    write_frame_until(
        pipe.0,
        &BootstrapFrame {
            magic: AUTH_MAGIC,
            ..hello
        },
        bootstrap_deadline,
    )?;
    Ok(ChildChannel {
        pipe,
        parent_pid,
        nonce,
        channel_id: mint_channel_id(),
        next_transfer_id: 1,
        pending_transcript: None,
        poisoned: false,
    })
}

/// Authenticated child endpoint retained for the lifetime of imported capabilities.
pub struct ChildChannel {
    pipe: OwnedHandle,
    parent_pid: u32,
    nonce: [u8; 32],
    channel_id: u64,
    next_transfer_id: u64,
    pending_transcript: Option<[u8; CONTROL_FRAME_LEN]>,
    poisoned: bool,
}
impl ChildChannel {
    /// Held authenticated parent PID.
    pub const fn parent_pid(&self) -> u32 {
        self.parent_pid
    }
    pub(crate) const fn vnext_nonce(&self) -> [u8; 32] {
        self.nonce
    }
    /// Raw pipe handle for a bounded manifest protocol owned by the caller.
    pub const fn pipe_handle(&self) -> HANDLE {
        self.pipe.0
    }
    /// Receives exact-rights handle values only after pipe PID authentication.
    ///
    /// The tuple is `(reader_handle, reader_len, writer_handle, writer_len)`.
    /// Lengths are exact page-rounded capability sizes. Handles remain pending
    /// and must be imported and passed to [`Self::commit_imports`].
    ///
    /// # Errors
    ///
    /// Returns an error for duplicate receipt, timeout, truncated or oversized
    /// frames, invalid fixed-width values, or a malformed capability envelope.
    pub fn receive_capabilities(
        &mut self,
    ) -> Result<(RemoteHandle, usize, RemoteHandle, usize), WindowsError> {
        if self.poisoned || self.pending_transcript.is_some() {
            return Err(WindowsError::InvalidBootstrap);
        }
        let frame: [u8; CAPABILITY_FRAME_LEN] = read_pod(self.pipe.0)?;
        if frame[..8] != CAPABILITY_MAGIC {
            return Err(WindowsError::InvalidBootstrap);
        }
        let reader_handle = usize::try_from(u64::from_le_bytes(
            frame[8..16].try_into().expect("fixed range"),
        ))
        .map_err(|_| WindowsError::InvalidBootstrap)?;
        let writer_handle = usize::try_from(u64::from_le_bytes(
            frame[16..24].try_into().expect("fixed range"),
        ))
        .map_err(|_| WindowsError::InvalidBootstrap)?;
        let reader_len = usize::try_from(u64::from_le_bytes(
            frame[24..32].try_into().expect("fixed range"),
        ))
        .map_err(|_| WindowsError::InvalidBootstrap)?;
        let writer_len = usize::try_from(u64::from_le_bytes(
            frame[32..40].try_into().expect("fixed range"),
        ))
        .map_err(|_| WindowsError::InvalidBootstrap)?;
        if reader_handle == 0 || writer_handle == 0 || reader_len == 0 || writer_len == 0 {
            return Err(WindowsError::InvalidBootstrap);
        }
        let mut transcript = [0; CONTROL_FRAME_LEN];
        transcript.copy_from_slice(&frame[40..]);
        self.pending_transcript = Some(transcript);
        Ok((
            RemoteHandle(reader_handle),
            reader_len,
            RemoteHandle(writer_handle),
            writer_len,
        ))
    }
    /// Imports a duplicated read-only section handle for this open transaction.
    ///
    /// The pending value is bound to this channel and its current transfer
    /// transaction; [`Self::commit_imports`] rejects values from any other
    /// channel or transaction.
    ///
    /// # Safety
    ///
    /// `handle` must have arrived over this channel's authenticated bootstrap,
    /// be owned by this process, have exactly the manifest rights, and not have
    /// been previously closed.
    pub unsafe fn import_reader(
        &self,
        handle: usize,
        len: usize,
        native: NativeRegionSpec,
        expected: ValidationExpectations,
        topology: RegionSetLayout,
    ) -> Result<PendingImportedReader, WindowsError> {
        let section = OwnedHandle::new(handle as HANDLE)?;
        let view = View::map(section.0, len, FILE_MAP_READ)?;
        // SAFETY: READY protocol keeps view quiescent; access is read-only.
        let bytes = unsafe { std::slice::from_raw_parts(view.base.as_ptr(), len) };
        let layout = unsafe { ValidatedRegionLayout::validate(bytes, expected, &topology) }?;
        if native.mapped_len != len as u64 {
            return Err(WindowsError::InvalidBootstrap);
        }
        let entry = ManifestEntry::from_native(native, PeerAccess::ReadOnly);
        drop(section);
        Ok(PendingImportedReader {
            runtime: ReaderRegion::new(WindowsReaderMapping { view }, layout, topology)
                .map_err(|(_, error)| error)?,
            entry,
            provenance: self.pending_provenance(),
        })
    }

    /// Imports the sole duplicated writer handle for this open transaction.
    ///
    /// # Safety
    ///
    /// Same authenticated ownership requirements as [`Self::import_reader`],
    /// plus the manifest/creator must guarantee no other writable handle or
    /// view exists.
    pub unsafe fn import_writer(
        &self,
        handle: usize,
        len: usize,
        native: NativeRegionSpec,
        expected: ValidationExpectations,
        topology: RegionSetLayout,
    ) -> Result<PendingImportedWriter, WindowsError> {
        let section = OwnedHandle::new(handle as HANDLE)?;
        let view = View::map(section.0, len, FILE_MAP_WRITE)?;
        // SAFETY: READY protocol keeps the sole writer quiescent during validation.
        let bytes = unsafe { std::slice::from_raw_parts(view.base.as_ptr(), len) };
        let layout = unsafe { ValidatedRegionLayout::validate(bytes, expected, &topology) }?;
        if native.mapped_len != len as u64 {
            return Err(WindowsError::InvalidBootstrap);
        }
        let entry = ManifestEntry::from_native(native, PeerAccess::SoleWriter);
        drop(section);
        Ok(PendingImportedWriter {
            runtime: WriterRegion::new(WindowsWriterMapping { view }, layout, topology)
                .map_err(|(_, error)| error)?,
            entry,
            provenance: self.pending_provenance(),
        })
    }

    /// Provenance stamp binding pending imports to the open transaction.
    const fn pending_provenance(&self) -> TransferProvenance {
        TransferProvenance::new(self.channel_id, self.next_transfer_id)
    }

    /// Signals validation, waits for COMMIT, then exposes imported capabilities.
    ///
    /// Returns `(imported_reader, imported_writer)` in manifest order.
    ///
    /// # Errors
    ///
    /// Returns an error if either pending value belongs to another channel or
    /// transfer transaction, the imported entries do not match the capability
    /// transcript, READY cannot be sent, or COMMIT is malformed or stale.
    pub fn commit_imports(
        &mut self,
        reader: PendingImportedReader,
        writer: PendingImportedWriter,
    ) -> Result<
        (
            ReaderRegion<WindowsReaderMapping>,
            WriterRegion<WindowsWriterMapping>,
        ),
        WindowsError,
    > {
        if self.poisoned {
            return Err(WindowsError::InvalidBootstrap);
        }
        let expected = self.pending_provenance();
        if reader.provenance != expected || writer.provenance != expected {
            self.poisoned = true;
            return Err(WindowsError::ForeignPending);
        }
        let manifest = TransferManifest::new(
            self.nonce,
            self.parent_pid,
            unsafe { GetCurrentProcessId() },
            self.next_transfer_id,
            vec![reader.entry, writer.entry],
        )
        .ok_or(WindowsError::InvalidBootstrap)?;
        let transcript = self
            .pending_transcript
            .as_ref()
            .ok_or(WindowsError::InvalidBootstrap)?;
        if !manifest.matches_frame(CAPABILITY_MAGIC, transcript) {
            return Err(WindowsError::InvalidBootstrap);
        }
        write_pod(self.pipe.0, &manifest.encode(READY_MAGIC))?;
        let commit: [u8; CONTROL_FRAME_LEN] = read_pod(self.pipe.0)?;
        if !manifest.matches_frame(COMMIT_MAGIC, &commit) {
            return Err(WindowsError::InvalidBootstrap);
        }
        self.pending_transcript = None;
        self.next_transfer_id = self
            .next_transfer_id
            .checked_add(1)
            .ok_or(WindowsError::InvalidBootstrap)?;
        Ok((reader.runtime, writer.runtime))
    }
}

/// Platform-minted unique writable unnamed-section view.
pub struct WindowsWriterMapping {
    view: View,
}
// SAFETY: constructors consume the full creator handle and retain the sole RW view.
unsafe impl SoleWriterMapping for WindowsWriterMapping {
    fn base(&self) -> NonNull<u8> {
        self.view.base
    }
    fn len(&self) -> usize {
        self.view.len
    }
}
/// Platform-minted read-only unnamed-section view.
pub struct WindowsReaderMapping {
    view: View,
}
// SAFETY: constructors map only FILE_MAP_READ and retain the view lifetime.
unsafe impl ReadOnlyMapping for WindowsReaderMapping {
    fn base(&self) -> NonNull<u8> {
        self.view.base
    }
    fn len(&self) -> usize {
        self.view.len
    }
}

struct OwnedHandle(HANDLE);
impl OwnedHandle {
    fn new(handle: HANDLE) -> Result<Self, WindowsError> {
        if handle.is_null() || handle == INVALID_HANDLE_VALUE {
            Err(WindowsError::InvalidHandle)
        } else {
            Ok(Self(handle))
        }
    }

    fn close(self) -> Result<(), WindowsError> {
        let this = std::mem::ManuallyDrop::new(self);
        // SAFETY: ManuallyDrop suppresses the destructor, so this is the one
        // close attempt for the uniquely owned real handle.
        if unsafe { CloseHandle(this.0) } == 0 {
            Err(last_os("CloseHandle"))
        } else {
            Ok(())
        }
    }
}
impl Drop for OwnedHandle {
    fn drop(&mut self) {
        // SAFETY: this value uniquely owns a real non-pseudo handle.
        let _ = unsafe { CloseHandle(self.0) };
    }
}

/// Reserved-placeholder bookkeeping for one guarded view: an inaccessible
/// reserved band placeholder sits immediately before and after the interior
/// placeholder the view was mapped into.
struct ViewGuardBands {
    lead: *mut core::ffi::c_void,
    interior: *mut core::ffi::c_void,
    tail: *mut core::ffi::c_void,
}

struct View {
    base: NonNull<u8>,
    len: usize,
    guard: Option<ViewGuardBands>,
}
impl View {
    fn map(section: HANDLE, len: usize, access: u32) -> Result<Self, WindowsError> {
        // SAFETY: section handle is live; access/offset/length are checked.
        let address = unsafe { MapViewOfFile(section, access, 0, 0, len) };
        let base = NonNull::new(address.Value.cast()).ok_or_else(|| last_os("MapViewOfFile"))?;
        Ok(Self {
            base,
            len,
            guard: None,
        })
    }

    /// Maps the view guarded where placeholder placement succeeds, otherwise
    /// falls back to the plain map with its original error semantics.
    fn map_with_guard(
        section: HANDLE,
        len: usize,
        access: u32,
        guard: bool,
    ) -> Result<Self, WindowsError> {
        if guard && let Some(view) = Self::map_guarded(section, len, access) {
            return Ok(view);
        }
        Self::map(section, len, access)
    }

    /// Best-effort guarded placement: one reserved placeholder of band, view,
    /// and band length is split into three placeholders, and the view replaces
    /// the middle one. The outer placeholders stay reserved and inaccessible.
    /// Any failure releases every placeholder and returns `None`.
    fn map_guarded(section: HANDLE, len: usize, access: u32) -> Option<Self> {
        let band = allocation_granularity()?;
        if len == 0 || !len.is_multiple_of(page_unit()?) {
            return None;
        }
        let total = len.checked_add(band.checked_mul(2)?)?;
        if total > isize::MAX as usize {
            return None;
        }
        // SAFETY: a fresh inaccessible reservation of checked length in the
        // current process; no extended constraints are supplied.
        let lead = unsafe {
            VirtualAlloc2(
                GetCurrentProcess(),
                std::ptr::null(),
                total,
                MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
                PAGE_NOACCESS,
                std::ptr::null_mut(),
                0,
            )
        };
        if lead.is_null() {
            return None;
        }
        // SAFETY: the split target is the base of the owned placeholder.
        if unsafe { VirtualFree(lead, band, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) } == 0 {
            // SAFETY: releasing the whole still-unsplit owned placeholder.
            let _ = unsafe { VirtualFree(lead, 0, MEM_RELEASE) };
            return None;
        }
        // SAFETY: `lead` is a live owned placeholder of exactly `band` bytes.
        let interior = unsafe { lead.cast::<u8>().add(band).cast::<core::ffi::c_void>() };
        // SAFETY: the split target is the base of the owned second placeholder.
        if unsafe { VirtualFree(interior, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) } == 0 {
            // SAFETY: releasing both owned placeholders exactly once each.
            let _ = unsafe { VirtualFree(lead, 0, MEM_RELEASE) };
            let _ = unsafe { VirtualFree(interior, 0, MEM_RELEASE) };
            return None;
        }
        // SAFETY: `interior` is a live owned placeholder of exactly `len`.
        let tail = unsafe { interior.cast::<u8>().add(len).cast::<core::ffi::c_void>() };
        let protection = if access == FILE_MAP_READ {
            PAGE_READONLY
        } else {
            PAGE_READWRITE
        };
        // SAFETY: the live section maps into the exactly sized owned interior
        // placeholder of the current process; no extended constraints.
        let address = unsafe {
            MapViewOfFile3(
                section,
                GetCurrentProcess(),
                interior,
                0,
                len,
                MEM_REPLACE_PLACEHOLDER,
                protection,
                std::ptr::null_mut(),
                0,
            )
        };
        let Some(base) = NonNull::new(address.Value.cast::<u8>()) else {
            // SAFETY: releasing all three owned placeholders exactly once.
            unsafe {
                let _ = VirtualFree(lead, 0, MEM_RELEASE);
                let _ = VirtualFree(interior, 0, MEM_RELEASE);
                let _ = VirtualFree(tail, 0, MEM_RELEASE);
            }
            return None;
        };
        if base.as_ptr() != interior.cast::<u8>() {
            // A replaced placeholder maps exactly at its base; anything else
            // forfeits the guarded placement.
            // SAFETY: the unexpected view and all placeholders remain owned.
            unsafe {
                let _ = UnmapViewOfFile2(
                    GetCurrentProcess(),
                    MEMORY_MAPPED_VIEW_ADDRESS {
                        Value: base.as_ptr().cast(),
                    },
                    MEM_PRESERVE_PLACEHOLDER,
                );
                let _ = VirtualFree(lead, 0, MEM_RELEASE);
                let _ = VirtualFree(interior, 0, MEM_RELEASE);
                let _ = VirtualFree(tail, 0, MEM_RELEASE);
            }
            return None;
        }
        Some(Self {
            base,
            len,
            guard: Some(ViewGuardBands {
                lead,
                interior,
                tail,
            }),
        })
    }

    fn release_native(&mut self) -> Result<(), WindowsError> {
        let Some(guard) = self.guard.take() else {
            // SAFETY: this object uniquely owns the mapped plain view.
            if unsafe {
                UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
                    Value: self.base.as_ptr().cast(),
                })
            } == 0
            {
                return Err(last_os("UnmapViewOfFile"));
            }
            return Ok(());
        };
        // Unmap the interior view first so it becomes a placeholder again,
        // then release each of the three placeholders exactly once.
        // SAFETY: this object uniquely owns the guarded view and placeholders.
        let unmapped = unsafe {
            UnmapViewOfFile2(
                GetCurrentProcess(),
                MEMORY_MAPPED_VIEW_ADDRESS {
                    Value: self.base.as_ptr().cast(),
                },
                MEM_PRESERVE_PLACEHOLDER,
            )
        };
        let mut first_error = if unmapped == 0 {
            Some(last_os("UnmapViewOfFile2"))
        } else {
            None
        };
        for placeholder in [guard.lead, guard.interior, guard.tail] {
            // SAFETY: each placeholder base is owned and released exactly once.
            if unsafe { VirtualFree(placeholder, 0, MEM_RELEASE) } == 0 && first_error.is_none() {
                first_error = Some(last_os("VirtualFree"));
            }
        }
        match first_error {
            Some(error) => Err(error),
            None => Ok(()),
        }
    }

    fn unmap(self) -> Result<(), WindowsError> {
        let mut this = std::mem::ManuallyDrop::new(self);
        // ManuallyDrop suppresses the destructor, so this is the one native
        // release attempt for the uniquely owned complete view.
        this.release_native()
    }
}
impl Drop for View {
    fn drop(&mut self) {
        let _ = self.release_native();
    }
}

/// System allocation granularity: the guard band unit that also satisfies the
/// fixed-address alignment rule for mapped section views.
fn allocation_granularity() -> Option<usize> {
    let mut information: SYSTEM_INFO = unsafe { zeroed() };
    // SAFETY: output pointer is valid.
    unsafe { GetSystemInfo(&mut information) };
    let granularity = information.dwAllocationGranularity as usize;
    let page = information.dwPageSize as usize;
    (granularity.is_power_of_two() && page.is_power_of_two() && granularity >= page)
        .then_some(granularity)
}

/// System page size for placeholder split alignment checks.
fn page_unit() -> Option<usize> {
    let mut information: SYSTEM_INFO = unsafe { zeroed() };
    // SAFETY: output pointer is valid.
    unsafe { GetSystemInfo(&mut information) };
    let page = information.dwPageSize as usize;
    page.is_power_of_two().then_some(page)
}

fn duplicate_to(source: HANDLE, target: HANDLE, access: u32) -> Result<RemoteHandle, WindowsError> {
    let mut remote: HANDLE = std::ptr::null_mut();
    // SAFETY: source/current/target handles are live; no SAME_ACCESS option is used.
    if unsafe {
        DuplicateHandle(
            GetCurrentProcess(),
            source,
            target,
            &mut remote,
            access,
            0,
            0,
        )
    } == 0
    {
        return Err(last_os("DuplicateHandle"));
    }
    if remote.is_null() {
        Err(WindowsError::InvalidHandle)
    } else {
        Ok(RemoteHandle(remote as usize))
    }
}

fn page_align(size: usize) -> Result<usize, WindowsError> {
    if size == 0 {
        return Err(WindowsError::InvalidSize(size));
    }
    let mut information: SYSTEM_INFO = unsafe { zeroed() };
    // SAFETY: output pointer is valid.
    unsafe { GetSystemInfo(&mut information) };
    let page = information.dwPageSize as usize;
    if page == 0 || !page.is_power_of_two() {
        return Err(WindowsError::InvalidSize(size));
    }
    size.checked_add(page - 1)
        .map(|value| value & !(page - 1))
        .filter(|value| *value <= isize::MAX as usize)
        .ok_or(WindowsError::InvalidSize(size))
}

fn wide_null(value: &OsStr) -> Vec<u16> {
    value.encode_wide().chain(std::iter::once(0)).collect()
}

fn quote_argument(value: &OsStr, output: &mut Vec<u16>) {
    let units: Vec<u16> = value.encode_wide().collect();
    let needs_quotes = units.is_empty()
        || units
            .iter()
            .any(|unit| *unit == b' ' as u16 || *unit == b'\t' as u16);
    if !needs_quotes {
        output.extend(units);
        return;
    }
    output.push(b'"' as u16);
    let mut slashes = 0;
    for unit in units {
        if unit == b'\\' as u16 {
            slashes += 1;
        } else if unit == b'"' as u16 {
            output.extend(std::iter::repeat_n(b'\\' as u16, slashes * 2 + 1));
            output.push(unit);
            slashes = 0;
        } else {
            output.extend(std::iter::repeat_n(b'\\' as u16, slashes));
            output.push(unit);
            slashes = 0;
        }
    }
    output.extend(std::iter::repeat_n(b'\\' as u16, slashes * 2));
    output.push(b'"' as u16);
}

fn command_line(path: &OsStr, arguments: &[OsString]) -> Vec<u16> {
    let mut result = Vec::new();
    quote_argument(path, &mut result);
    for argument in arguments {
        result.push(b' ' as u16);
        quote_argument(argument, &mut result);
    }
    result.push(0);
    result
}
// SAFETY: the channel uniquely owns its authenticated pipe handle and mutable
// protocol state. It is moved as one non-Sync value.
unsafe impl Send for ChildChannel {}

fn command_line_exact(arguments: &[OsString]) -> Vec<u16> {
    let mut result = Vec::new();
    for (index, argument) in arguments.iter().enumerate() {
        if index != 0 {
            result.push(b' ' as u16);
        }
        quote_argument(argument, &mut result);
    }
    result.push(0);
    result
}

pub(super) fn public_command_strings_are_valid(
    path: &Path,
    arguments: &[OsString],
    environment: &[(OsString, OsString)],
) -> bool {
    let has_nul = |value: &OsStr| value.encode_wide().any(|unit| unit == 0);
    if has_nul(path.as_os_str()) || arguments.iter().any(|argument| has_nul(argument)) {
        return false;
    }
    let reserved = [PIPE_ENV, NONCE_ENV, PARENT_ENV, PUBLIC_BOOTSTRAP_ENV];
    for (index, (key, value)) in environment.iter().enumerate() {
        let key_text = key.to_string_lossy();
        if key.is_empty()
            || has_nul(key)
            || key_text.contains('=')
            || has_nul(value)
            || reserved
                .iter()
                .any(|name| key_text.eq_ignore_ascii_case(name))
            || environment[..index]
                .iter()
                .any(|(existing, _)| existing.to_string_lossy().eq_ignore_ascii_case(&key_text))
        {
            return false;
        }
    }
    true
}

fn environment_block_exact(
    explicit: &[(OsString, OsString)],
    bootstrap: &[(&str, String)],
) -> Result<Vec<u16>, WindowsError> {
    let mut values = explicit.to_vec();
    for (name, value) in bootstrap {
        if values
            .iter()
            .any(|(key, _)| key.to_string_lossy().eq_ignore_ascii_case(name))
        {
            return Err(WindowsError::InvalidBootstrap);
        }
        values.push((OsString::from(name), OsString::from(value)));
    }
    values.sort_by(|left, right| {
        left.0
            .to_string_lossy()
            .to_ascii_lowercase()
            .cmp(&right.0.to_string_lossy().to_ascii_lowercase())
    });
    if values.windows(2).any(|pair| {
        pair[0]
            .0
            .to_string_lossy()
            .eq_ignore_ascii_case(&pair[1].0.to_string_lossy())
    }) {
        return Err(WindowsError::InvalidBootstrap);
    }
    let mut block = Vec::new();
    for (key, value) in values {
        let key = key.to_string_lossy();
        if key.is_empty() || key.contains('=') || key.contains('\0') {
            return Err(WindowsError::InvalidBootstrap);
        }
        let value = value.to_string_lossy();
        if value.contains('\0') {
            return Err(WindowsError::InvalidBootstrap);
        }
        block.extend(key.encode_utf16());
        block.push(b'=' as u16);
        block.extend(value.encode_utf16());
        block.push(0);
    }
    block.push(0);
    Ok(block)
}

fn environment_block(overrides: &[(&str, String)]) -> Vec<u16> {
    let mut values: Vec<(OsString, OsString)> = std::env::vars_os()
        .filter(|(key, _)| {
            !overrides
                .iter()
                .any(|(name, _)| key.to_string_lossy().eq_ignore_ascii_case(name))
        })
        .collect();
    values.extend(
        overrides
            .iter()
            .map(|(key, value)| (OsString::from(key), OsString::from(value))),
    );
    values.sort_by(|left, right| {
        left.0
            .to_string_lossy()
            .to_ascii_lowercase()
            .cmp(&right.0.to_string_lossy().to_ascii_lowercase())
    });
    let mut block = Vec::new();
    for (key, value) in values {
        block.extend(key.encode_wide());
        block.push(b'=' as u16);
        block.extend(value.encode_wide());
        block.push(0);
    }
    block.push(0);
    block
}

fn pod_bytes<T>(value: &T) -> &[u8] {
    // SAFETY: callers use repr(C), fully initialized integer-only protocol records.
    unsafe { std::slice::from_raw_parts((value as *const T).cast(), size_of::<T>()) }
}

fn write_frame_until(
    pipe: HANDLE,
    frame: &BootstrapFrame,
    deadline: Instant,
) -> Result<(), WindowsError> {
    write_pod_until(pipe, frame, deadline)
}

fn write_pod<T>(pipe: HANDLE, value: &T) -> Result<(), WindowsError> {
    let deadline = Instant::now() + Duration::from_millis(WAIT_MS.into());
    write_pod_until(pipe, value, deadline)
}

fn write_pod_until<T>(pipe: HANDLE, value: &T, deadline: Instant) -> Result<(), WindowsError> {
    let bytes = pod_bytes(value);
    loop {
        let mut written = 0;
        // SAFETY: pipe is live, bytes are valid, and nonblocking operation is synchronous.
        if unsafe {
            WriteFile(
                pipe,
                bytes.as_ptr(),
                bytes.len() as u32,
                &mut written,
                std::ptr::null_mut(),
            )
        } != 0
        {
            if written as usize != bytes.len() || Instant::now() >= deadline {
                return Err(WindowsError::InvalidBootstrap);
            }
            return Ok(());
        }
        let code = unsafe { GetLastError() };
        if code != ERROR_NO_DATA && code != ERROR_PIPE_LISTENING {
            return Err(WindowsError::Os {
                operation: "WriteFile",
                code,
            });
        }
        wait_retry(deadline, "pipe write")?;
    }
}

fn read_frame_until(pipe: HANDLE, deadline: Instant) -> Result<BootstrapFrame, WindowsError> {
    read_pod_until(pipe, deadline)
}

fn read_pod<T>(pipe: HANDLE) -> Result<T, WindowsError> {
    let deadline = Instant::now() + Duration::from_millis(WAIT_MS.into());
    read_pod_until(pipe, deadline)
}

fn read_pod_until<T>(pipe: HANDLE, deadline: Instant) -> Result<T, WindowsError> {
    loop {
        let mut value: T = unsafe { zeroed() };
        let mut read = 0;
        // SAFETY: frame output range is valid and nonblocking operation is synchronous.
        if unsafe {
            ReadFile(
                pipe,
                (&mut value as *mut T).cast(),
                size_of::<T>() as u32,
                &mut read,
                std::ptr::null_mut(),
            )
        } != 0
        {
            if read as usize != size_of::<T>() || Instant::now() >= deadline {
                return Err(WindowsError::InvalidBootstrap);
            }
            return Ok(value);
        }
        let code = unsafe { GetLastError() };
        if code != ERROR_NO_DATA && code != ERROR_PIPE_LISTENING {
            return Err(WindowsError::Os {
                operation: "ReadFile",
                code,
            });
        }
        wait_retry(deadline, "pipe read")?;
    }
}

fn connect_authenticated_pipe(
    pipe: HANDLE,
    process: HANDLE,
    expected_pid: u32,
    deadline: Instant,
) -> Result<(), WindowsError> {
    loop {
        check_instant_deadline(deadline, "authenticated pipe connect")?;
        connect_pipe_until(pipe, process, deadline)?;
        // SAFETY: the server pipe is connected and the expected PID is held live.
        match unsafe { authenticate_pipe_client(pipe, expected_pid) } {
            Ok(()) => {
                check_instant_deadline(deadline, "authenticated pipe connect")?;
                return Ok(());
            }
            Err(WindowsError::WrongPeer) => {
                // SAFETY: this server owns the connected one-instance pipe.
                if unsafe { DisconnectNamedPipe(pipe) } == 0 {
                    let code = unsafe { GetLastError() };
                    if code != ERROR_PIPE_NOT_CONNECTED && code != ERROR_BROKEN_PIPE {
                        return Err(WindowsError::Os {
                            operation: "DisconnectNamedPipe",
                            code,
                        });
                    }
                }
                wait_retry(deadline, "authenticated pipe connect")?;
            }
            Err(WindowsError::Os { code, .. })
                if code == ERROR_PIPE_NOT_CONNECTED || code == ERROR_BROKEN_PIPE =>
            {
                let _ = unsafe { DisconnectNamedPipe(pipe) };
                wait_retry(deadline, "authenticated pipe connect")?;
            }
            Err(error) => return Err(error),
        }
    }
}

fn connect_pipe_until(
    pipe: HANDLE,
    process: HANDLE,
    deadline: Instant,
) -> Result<(), WindowsError> {
    loop {
        check_instant_deadline(deadline, "pipe connect")?;
        // SAFETY: server pipe is nonblocking and no OVERLAPPED operation is requested.
        if unsafe { ConnectNamedPipe(pipe, std::ptr::null_mut()) } != 0 {
            check_instant_deadline(deadline, "pipe connect")?;
            return Ok(());
        }
        let code = unsafe { GetLastError() };
        if code == ERROR_PIPE_CONNECTED {
            check_instant_deadline(deadline, "pipe connect")?;
            return Ok(());
        }
        if code != ERROR_PIPE_LISTENING && code != ERROR_NO_DATA {
            return Err(WindowsError::Os {
                operation: "ConnectNamedPipe",
                code,
            });
        }
        // SAFETY: exact child process handle is held throughout bootstrap.
        if unsafe { WaitForSingleObject(process, 0) } == WAIT_OBJECT_0 {
            let mut exit = 0;
            // SAFETY: process is signaled and output is valid.
            if unsafe { GetExitCodeProcess(process, &mut exit) } != 0 {
                return Err(WindowsError::ChildExit(exit));
            }
            return Err(last_os("GetExitCodeProcess"));
        }
        wait_retry(deadline, "pipe connect")?;
    }
}

fn open_pipe_until(name: *const u16, deadline: Instant) -> Result<OwnedHandle, WindowsError> {
    loop {
        check_instant_deadline(deadline, "pipe open")?;
        // SAFETY: terminated name; no sharing or inheritance and existing pipe only.
        let pipe = unsafe {
            CreateFileW(
                name,
                GENERIC_READ | GENERIC_WRITE,
                0,
                std::ptr::null(),
                OPEN_EXISTING,
                0,
                std::ptr::null_mut(),
            )
        };
        if pipe != INVALID_HANDLE_VALUE && !pipe.is_null() {
            let pipe = OwnedHandle::new(pipe)?;
            check_instant_deadline(deadline, "pipe open")?;
            return Ok(pipe);
        }
        let code = unsafe { GetLastError() };
        if code != ERROR_PIPE_BUSY {
            return Err(WindowsError::Os {
                operation: "CreateFileW(pipe)",
                code,
            });
        }
        wait_retry(deadline, "pipe open")?;
    }
}

fn wait_retry(deadline: Instant, operation: &'static str) -> Result<(), WindowsError> {
    check_instant_deadline(deadline, operation)?;
    std::thread::sleep(
        Duration::from_millis(1).min(deadline.saturating_duration_since(Instant::now())),
    );
    check_instant_deadline(deadline, operation)
}

fn check_instant_deadline(deadline: Instant, operation: &'static str) -> Result<(), WindowsError> {
    if Instant::now() >= deadline {
        Err(WindowsError::TimedOut(operation))
    } else {
        Ok(())
    }
}

fn hex(bytes: &[u8; 32]) -> String {
    let mut output = String::with_capacity(64);
    for byte in bytes {
        use std::fmt::Write as _;
        write!(&mut output, "{byte:02x}").expect("String writes are infallible");
    }
    output
}

fn parse_nonce(value: &str) -> Result<[u8; 32], WindowsError> {
    if value.len() != 64 {
        return Err(WindowsError::InvalidBootstrap);
    }
    let mut nonce = [0; 32];
    for (index, output) in nonce.iter_mut().enumerate() {
        *output = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)
            .map_err(|_| WindowsError::InvalidBootstrap)?;
    }
    if nonce == [0; 32] {
        return Err(WindowsError::InvalidBootstrap);
    }
    Ok(nonce)
}

fn last_os(operation: &'static str) -> WindowsError {
    // SAFETY: GetLastError has no preconditions.
    WindowsError::Os {
        operation,
        code: unsafe { GetLastError() },
    }
}

#[path = "windows_vnext/memory.rs"]
pub(crate) mod vnext_memory;

#[path = "windows_vnext/transport.rs"]
pub(crate) mod vnext_transport;

#[path = "windows_vnext/session.rs"]
pub(crate) mod vnext_session;

#[cfg(test)]
#[path = "windows_vnext/memory_test.rs"]
mod vnext_memory_test;

#[cfg(test)]
#[path = "windows_vnext/transport_test.rs"]
mod vnext_transport_test;

#[cfg(test)]
#[path = "windows_vnext/reducer_test.rs"]
mod vnext_reducer_test;

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