oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
//! `fs` on Windows.

use core::ffi::c_void;
use core::ptr;

use crate::fs::{
    FileTimes, FileType, LockKind, Metadata, OpenOptions, RawDirEntry, Space, UnixMetadata,
};
use crate::path::{wide_to_wtf8, with_wide};
use crate::sys::io::{IoStatusBlock, Overlapped, STATUS_PENDING, completed, wait_completion};
use crate::sys::{cvt, dll, last_error};
use crate::time::Timestamp;
use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};

/// `FILETIME`: 100 ns intervals since 1601-01-01, in two halves.
#[derive(Clone, Copy, Default)]
#[repr(C)]
struct FileTime {
    low: u32,
    high: u32,
}

/// `BY_HANDLE_FILE_INFORMATION`.
#[derive(Default)]
#[repr(C)]
struct ByHandleFileInformation {
    attributes: u32,
    creation_time: FileTime,
    last_access_time: FileTime,
    last_write_time: FileTime,
    volume_serial_number: u32,
    file_size_high: u32,
    file_size_low: u32,
    number_of_links: u32,
    file_index_high: u32,
    file_index_low: u32,
}

/// `FILE_BASIC_INFO`. A time of zero leaves the file's as it is.
#[derive(Default)]
#[repr(C)]
struct FileBasicInfo {
    creation_time: i64,
    last_access_time: i64,
    last_write_time: i64,
    change_time: i64,
    attributes: u32,
}

/// `FILE_ATTRIBUTE_TAG_INFO`.
#[derive(Default)]
#[repr(C)]
struct FileAttributeTagInfo {
    attributes: u32,
    reparse_tag: u32,
}

dll!("kernel32.dll" {
    fn CreateFileW(
        name: *const u16,
        access: u32,
        share: u32,
        security: *const c_void,
        creation: u32,
        flags: u32,
        template: *mut c_void,
    ) -> *mut c_void;
    fn SetLastError(code: u32);
    fn GetFileType(handle: *mut c_void) -> u32;
    fn GetFileInformationByHandle(handle: *mut c_void, info: *mut ByHandleFileInformation) -> i32;
    fn GetFileInformationByHandleEx(
        handle: *mut c_void,
        class: i32,
        info: *mut c_void,
        size: u32,
    ) -> i32;
    fn SetFileInformationByHandle(
        handle: *mut c_void,
        class: i32,
        info: *const c_void,
        size: u32,
    ) -> i32;
    fn FlushFileBuffers(handle: *mut c_void) -> i32;
    fn SetFileTime(
        handle: *mut c_void,
        creation: *const FileTime,
        access: *const FileTime,
        write: *const FileTime,
    ) -> i32;
    fn LockFileEx(
        handle: *mut c_void,
        flags: u32,
        reserved: u32,
        len_low: u32,
        len_high: u32,
        overlapped: *mut Overlapped,
    ) -> i32;
    fn CreateEventW(
        security: *const c_void,
        manual_reset: i32,
        initial_state: i32,
        name: *const u16,
    ) -> *mut c_void;
    fn UnlockFile(
        handle: *mut c_void,
        offset_low: u32,
        offset_high: u32,
        len_low: u32,
        len_high: u32,
    ) -> i32;
    fn GetFileAttributesW(name: *const u16) -> u32;
    fn CreateDirectoryW(name: *const u16, security: *const c_void) -> i32;
    fn RemoveDirectoryW(name: *const u16) -> i32;
    fn DeleteFileW(name: *const u16) -> i32;
    fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32;
    fn CreateHardLinkW(link: *const u16, original: *const u16, security: *const c_void) -> i32;
    // It returns a `BOOLEAN`, one byte, unlike the others.
    fn CreateSymbolicLinkW(link: *const u16, target: *const u16, flags: u32) -> u8;
    fn DeviceIoControl(
        handle: *mut c_void,
        code: u32,
        input: *const c_void,
        input_size: u32,
        output: *mut c_void,
        output_size: u32,
        returned: *mut u32,
        overlapped: *mut Overlapped,
    ) -> i32;
    fn GetFinalPathNameByHandleW(handle: *mut c_void, path: *mut u16, len: u32, flags: u32)
    -> u32;
    fn GetCurrentDirectoryW(len: u32, path: *mut u16) -> u32;
    fn CopyFileExW(
        from: *const u16,
        to: *const u16,
        progress: Option<ProgressRoutine>,
        data: *const c_void,
        cancel: *mut i32,
        flags: u32,
    ) -> i32;
    fn GetFullPathNameW(path: *const u16, len: u32, buf: *mut u16, file_part: *mut *mut u16)
    -> u32;
    fn SetCurrentDirectoryW(path: *const u16) -> i32;
});

/// `UNICODE_STRING`: a counted wide string, with its lengths in bytes.
#[repr(C)]
struct UnicodeString {
    len: u16,
    capacity: u16,
    buf: *const u16,
}

/// `OBJECT_ATTRIBUTES`.
#[repr(C)]
struct ObjectAttributes {
    len: u32,
    root: *mut c_void,
    name: *const UnicodeString,
    attributes: u32,
    security_descriptor: *const c_void,
    security_qos: *const c_void,
}

dll!("ntdll.dll" {
    fn NtCreateFile(
        handle: *mut *mut c_void,
        access: u32,
        attributes: *const ObjectAttributes,
        status: *mut IoStatusBlock,
        allocation_size: *const i64,
        file_attributes: u32,
        share: u32,
        disposition: u32,
        options: u32,
        ea: *const c_void,
        ea_len: u32,
    ) -> i32;
    // What listing a directory is made of. The two `BOOLEAN`s are one byte.
    fn NtQueryDirectoryFile(
        handle: *mut c_void,
        event: *mut c_void,
        apc_routine: *const c_void,
        apc_context: *const c_void,
        status: *mut IoStatusBlock,
        info: *mut c_void,
        len: u32,
        class: i32,
        single_entry: u8,
        name: *const UnicodeString,
        restart: u8,
    ) -> i32;
    fn NtSetInformationFile(
        handle: *mut c_void,
        status: *mut IoStatusBlock,
        info: *const c_void,
        len: u32,
        class: i32,
    ) -> i32;
    fn NtQueryVolumeInformationFile(
        handle: *mut c_void,
        status: *mut IoStatusBlock,
        info: *mut c_void,
        len: u32,
        class: i32,
    ) -> i32;
});

/// `LPPROGRESS_ROUTINE`.
type ProgressRoutine = unsafe extern "system" fn(
    total_size: i64,
    total_transferred: i64,
    stream_size: i64,
    stream_transferred: i64,
    stream: u32,
    reason: u32,
    source: *mut c_void,
    destination: *mut c_void,
    data: *const c_void,
) -> u32;

/// `FILE_STANDARD_INFO`.
#[derive(Default)]
#[repr(C)]
struct FileStandardInfo {
    allocation_size: i64,
    end_of_file: i64,
    links: u32,
    delete_pending: u8,
    directory: u8,
}

/// `FILE_FS_FULL_SIZE_INFORMATION`.
#[derive(Default)]
#[repr(C)]
struct FileFsFullSizeInformation {
    total_units: i64,
    caller_available_units: i64,
    actual_available_units: i64,
    sectors_per_unit: u32,
    bytes_per_sector: u32,
}

// FS_INFORMATION_CLASS
const FILE_FS_FULL_SIZE_INFORMATION: i32 = 7;

const GENERIC_READ: u32 = 0x8000_0000;
const GENERIC_WRITE: u32 = 0x4000_0000;
const FILE_WRITE_DATA: u32 = 0x2;
const FILE_READ_ATTRIBUTES: u32 = 0x80;
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
const FILE_GENERIC_WRITE: u32 = 0x12_0116;

const FILE_LIST_DIRECTORY: u32 = 0x1;
const DELETE: u32 = 0x1_0000;
const SYNCHRONIZE: u32 = 0x10_0000;

const FILE_SHARE_ALL: u32 = 0x1 | 0x2 | 0x4; // read, write, delete

// The dispositions of `NtCreateFile`, and what it answers.
const FILE_OPEN: u32 = 1;
const FILE_CREATE: u32 = 2;
const FILE_OPEN_IF: u32 = 3;
const FILE_OVERWRITE: u32 = 4;
const FILE_OPENED: usize = 1;

// Its options.
const FILE_DIRECTORY_FILE: u32 = 0x1;
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x20;
const FILE_NON_DIRECTORY_FILE: u32 = 0x40;
const FILE_OPEN_FOR_BACKUP_INTENT: u32 = 0x4000;
const FILE_OPEN_REPARSE_POINT: u32 = 0x20_0000;

const OBJ_CASE_INSENSITIVE: u32 = 0x40;

const STATUS_FILE_IS_A_DIRECTORY: i32 = 0xc000_00ba_u32 as i32;

// FILE_INFORMATION_CLASS
const FILE_RENAME_INFORMATION: i32 = 10;
const FILE_LINK_INFORMATION: i32 = 11;

const FILE_DISPOSITION_DELETE: u32 = 0x1;
const FILE_DISPOSITION_POSIX_SEMANTICS: u32 = 0x2;

const CREATE_NEW: u32 = 1;
const OPEN_EXISTING: u32 = 3;
const OPEN_ALWAYS: u32 = 4;
const TRUNCATE_EXISTING: u32 = 5;

const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x20_0000;
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x200_0000;

const FILE_ATTRIBUTE_READONLY: u32 = 0x1;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;

// FILE_INFO_BY_HANDLE_CLASS
const FILE_BASIC_INFO: i32 = 0;
const FILE_STANDARD_INFO: i32 = 1;
const FILE_ALLOCATION_INFO: i32 = 5;
const FILE_DISPOSITION_INFO: i32 = 4;
const FILE_END_OF_FILE_INFO: i32 = 6;
const FILE_ATTRIBUTE_TAG_INFO: i32 = 9;
// FILE_INFORMATION_CLASS
/// It writes `FILE_ID_BOTH_DIR_INFORMATION`, which is the
/// `FILE_ID_BOTH_DIR_INFO` of Win32.
const FILE_ID_BOTH_DIRECTORY_INFORMATION: i32 = 37;
const FILE_DISPOSITION_INFO_EX: i32 = 21;

const FILE_TYPE_DISK: u32 = 1;
const FILE_TYPE_CHAR: u32 = 2;
const FILE_TYPE_PIPE: u32 = 3;

const LOCKFILE_FAIL_IMMEDIATELY: u32 = 1;
const LOCKFILE_EXCLUSIVE_LOCK: u32 = 2;

const MOVEFILE_REPLACE_EXISTING: u32 = 1;

const SYMBOLIC_LINK_FLAG_DIRECTORY: u32 = 1;
const SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: u32 = 2;

const FSCTL_SET_REPARSE_POINT: u32 = 0x9_00a4;
const FSCTL_GET_REPARSE_POINT: u32 = 0x9_00a8;
const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16384;
const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xa000_0003;
const IO_REPARSE_TAG_SYMLINK: u32 = 0xa000_000c;
/// The bit of a reparse tag that says the reparse point stands for another
/// name: a symbolic link or a junction, as opposed to, say, a cloud file.
const REPARSE_TAG_NAME_SURROGATE: u32 = 0x2000_0000;
const SYMLINK_FLAG_RELATIVE: u32 = 1;
/// What `SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE` becomes in the
/// reparse data `CreateSymbolicLinkW` writes.
const SYMLINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: u32 = 2;

const ERROR_INVALID_FUNCTION: i32 = 1;
const ERROR_ACCESS_DENIED: i32 = 5;
const ERROR_NOT_SUPPORTED: i32 = 50;
const ERROR_NO_MORE_FILES: i32 = 18;
const ERROR_SHARING_VIOLATION: i32 = 32;
const ERROR_LOCK_VIOLATION: i32 = 33;
const ERROR_INVALID_PARAMETER: i32 = 87;
const ERROR_NOT_LOCKED: i32 = 158;
const ERROR_ALREADY_EXISTS: i32 = 183;
const ERROR_DIRECTORY: i32 = 267;
const ERROR_DIRECTORY_NOT_SUPPORTED: i32 = 336;
const ERROR_IO_PENDING: i32 = 997;
const ERROR_CANT_RESOLVE_FILENAME: i32 = 1921;
const ERROR_NOT_A_REPARSE_POINT: i32 = 4390;

/// Seconds from 1601-01-01 to 1970-01-01.
const EPOCH_DIFFERENCE: i64 = 11_644_473_600;
/// `FILETIME` units in a second.
const INTERVALS_PER_SEC: u64 = 10_000_000;

/// The longest path Win32 takes as it is, with its NUL. `MAX_PATH` is 260,
/// but a directory must leave room for a short file name (8.3) in it.
const LEGACY_MAX_PATH: usize = 248;

/// Calls `f` with `path` as NUL-terminated UTF-16, like `with_wide`, and in
/// the form Win32 takes a long path in when it is one.
///
/// Win32 refuses a path of `MAX_PATH` units or more, unless it is in the
/// extended form: absolute, without `.`, `..` or `/`, and after `\\?\`.
/// (The limit can be lifted for a whole program, by its manifest and a
/// setting of the system at once: nothing a library can count on.) Like
/// `std`, a path whose absolute form is too long is given in that form,
/// which the system computes itself; any other path is given as it is.
fn with_path<R>(path: &[u8], f: impl FnOnce(&[u16]) -> Result<R>) -> Result<R> {
    const SEP: u16 = b'\\' as u16;
    const QUERY: u16 = b'?' as u16;
    const COLON: u16 = b':' as u16;
    const DOT: u16 = b'.' as u16;
    // `\\?\`, and `\\?\UNC\` for `\\server\share`.
    const VERBATIM: [u16; 4] = [SEP, SEP, QUERY, SEP];
    const VERBATIM_UNC: [u16; 8] = [
        SEP,
        SEP,
        QUERY,
        SEP,
        b'U' as u16,
        b'N' as u16,
        b'C' as u16,
        SEP,
    ];
    /// The room kept in front of the absolute path for its prefix.
    const ROOM: usize = VERBATIM_UNC.len();

    /// Calls `f` with the absolute path of `full` units that the system
    /// wrote after `ROOM` units of `buf`, in the extended form if it needs
    /// it, or with `original` if it does not.
    fn finish<R>(
        buf: &mut [u16],
        full: usize,
        original: &[u16],
        f: impl FnOnce(&[u16]) -> Result<R>,
    ) -> Result<R> {
        if full + 1 < LEGACY_MAX_PATH {
            return f(original);
        }
        let (skip, prefix): (usize, &[u16]) = match &buf[ROOM..ROOM + full] {
            // `C:\dir` becomes `\\?\C:\dir`.
            [_, COLON, SEP, ..] => (0, &VERBATIM),
            // `\\.\device` becomes `\\?\device`.
            [SEP, SEP, DOT, SEP, ..] => (4, &VERBATIM),
            // Already in that form, or in the kernel's (`\??\`).
            [SEP, SEP, QUERY, SEP, ..] | [SEP, QUERY, QUERY, SEP, ..] => (0, &[]),
            // `\\server\share` becomes `\\?\UNC\server\share`.
            [SEP, SEP, ..] => (2, &VERBATIM_UNC),
            _ => (0, &[]),
        };
        let start = ROOM + skip - prefix.len();
        buf[start..start + prefix.len()].copy_from_slice(prefix);
        // With the NUL the system wrote after the path.
        f(&buf[start..=ROOM + full])
    }

    with_wide(path, |wide| {
        let is_separator = |c: u16| c == SEP || c == b'/' as u16;
        // Without the NUL.
        let len = wide.len() - 1;
        if len == 0 || wide.starts_with(&VERBATIM) || wide.starts_with(&[SEP, QUERY, QUERY, SEP]) {
            return f(wide);
        }
        if len < LEGACY_MAX_PATH {
            // Short and absolute: nothing to compute. (A short relative
            // path can still be long, with the current directory.)
            let drive =
                wide[1] == COLON && !is_separator(wide[0]) && (len == 2 || is_separator(wide[2]));
            let unc = len >= 2 && is_separator(wide[0]) && is_separator(wide[1]);
            if drive || unc {
                return f(wide);
            }
        }
        let full_path = |buf: &mut [u16]| {
            let room = &mut buf[ROOM..];
            // SAFETY: `wide` is a NUL-terminated wide string, and the
            // buffer is writable for the length given.
            let full = unsafe {
                GetFullPathNameW(
                    wide.as_ptr(),
                    room.len().min(u32::MAX as usize) as u32,
                    room.as_mut_ptr(),
                    ptr::null_mut(),
                )
            } as usize;
            if full == 0 {
                Err(last_error())
            } else {
                Ok(full)
            }
        };
        let mut stack = [0u16; 1024];
        // The length of the path without its NUL when it fits, the size it
        // needs with it when it does not.
        let full = full_path(&mut stack)?;
        if full < stack.len() - ROOM {
            return finish(&mut stack, full, wide, f);
        }
        #[cfg(feature = "alloc")]
        {
            let mut heap = alloc::vec::Vec::new();
            heap.try_reserve_exact(ROOM + full)
                .map_err(|_| ErrorKind::OutOfMemory)?;
            heap.resize(ROOM + full, 0u16);
            let full = full_path(&mut heap)?;
            if full < heap.len() - ROOM {
                return finish(&mut heap, full, wide, f);
            }
        }
        // As for the paths given to oscall: long ones need `alloc`.
        Err(ErrorKind::InvalidFilename.into())
    })
}

/// `CreateFileW`, with every sharing mode and no inheritance.
fn create_file(path: &[u16], access: u32, creation: u32, flags: u32) -> Result<OwnedHandle> {
    // SAFETY: `path` is a NUL-terminated wide string. Without security
    // attributes the handle is not inheritable.
    let handle = unsafe {
        CreateFileW(
            path.as_ptr(),
            access,
            FILE_SHARE_ALL,
            ptr::null(),
            creation,
            flags,
            ptr::null_mut(),
        )
    };
    if handle as isize == -1 {
        return Err(last_error());
    }
    // SAFETY: the handle was just created.
    Ok(unsafe { OwnedHandle::from_raw(handle) })
}

/// The attributes of what `path` names, without following a link.
fn attributes_of(path: &[u16]) -> Option<u32> {
    // SAFETY: `path` is a NUL-terminated wide string.
    let attributes = unsafe { GetFileAttributesW(path.as_ptr()) };
    (attributes != INVALID_FILE_ATTRIBUTES).then_some(attributes)
}

fn is_dir(path: &[u16]) -> bool {
    attributes_of(path).is_some_and(|attributes| attributes & FILE_ATTRIBUTE_DIRECTORY != 0)
}

fn attribute_tag(handle: BorrowedHandle<'_>) -> Result<FileAttributeTagInfo> {
    let mut info = FileAttributeTagInfo::default();
    // SAFETY: `info` is the structure of this class, of the size given.
    cvt(unsafe {
        GetFileInformationByHandleEx(
            handle.as_raw(),
            FILE_ATTRIBUTE_TAG_INFO,
            (&raw mut info).cast(),
            size_of::<FileAttributeTagInfo>() as u32,
        )
    })?;
    Ok(info)
}

/// Whether the attributes and the reparse tag are those of a symbolic link
/// or of a junction.
fn is_link(attributes: u32, reparse_tag: u32) -> bool {
    attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 && reparse_tag & REPARSE_TAG_NAME_SURROGATE != 0
}

pub(crate) fn open(path: &[u8], options: &OpenOptions) -> Result<OwnedHandle> {
    // As `std`: appending is the right to write less the right to write
    // anywhere but at the end.
    let mut access = 0;
    if options.read {
        access |= GENERIC_READ;
    }
    if options.append {
        access |= FILE_GENERIC_WRITE & !FILE_WRITE_DATA;
    } else if options.write {
        access |= GENERIC_WRITE;
    }
    let truncate_existing = options.create && options.truncate && !options.create_new;
    let creation = if options.create_new {
        CREATE_NEW
    } else {
        match (options.create, options.truncate) {
            (false, false) => OPEN_EXISTING,
            (false, true) => TRUNCATE_EXISTING,
            // CREATE_ALWAYS is not what truncating means: it fails on a
            // hidden file and replaces the attributes. Like `std`, open
            // or create, then empty a file that was there.
            (true, _) => OPEN_ALWAYS,
        }
    };
    let mut flags = 0;
    if options.directory {
        flags |= FILE_FLAG_BACKUP_SEMANTICS;
    }
    if options.no_follow || options.create_new {
        flags |= FILE_FLAG_OPEN_REPARSE_POINT;
    }

    with_path(path, |path| {
        let handle = match create_file(path, access, creation, flags) {
            Ok(handle) => handle,
            Err(error) => {
                // A directory opened as a file is refused as "access
                // denied": say what the other systems say.
                if error.raw_os_error() == ERROR_ACCESS_DENIED && !options.directory && is_dir(path)
                {
                    return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
                }
                return Err(error);
            }
        };
        // OPEN_ALWAYS says through the last error whether the file existed.
        if truncate_existing && last_error().raw_os_error() == ERROR_ALREADY_EXISTS {
            set_len(handle.as_handle(), 0)?;
        }
        if options.no_follow || options.directory {
            let info = attribute_tag(handle.as_handle())?;
            if options.no_follow && is_link(info.attributes, info.reparse_tag) {
                return Err(Error::from_raw_os_error(ERROR_CANT_RESOLVE_FILENAME));
            }
            if options.directory && info.attributes & FILE_ATTRIBUTE_DIRECTORY == 0 {
                return Err(Error::from_raw_os_error(ERROR_DIRECTORY));
            }
        }
        Ok(handle)
    })
}

fn timestamp(time: FileTime) -> Timestamp {
    let intervals = (time.high as u64) << 32 | time.low as u64;
    Timestamp {
        secs: (intervals / INTERVALS_PER_SEC) as i64 - EPOCH_DIFFERENCE,
        nanos: (intervals % INTERVALS_PER_SEC) as u32 * 100,
    }
}

/// A timestamp as a `FILETIME`, if it can be one. Zero cannot be set: it
/// means "leave as it is" to the system.
fn file_time(time: Timestamp) -> Result<FileTime> {
    time.secs
        .checked_add(EPOCH_DIFFERENCE)
        .and_then(|secs| u64::try_from(secs).ok())
        .and_then(|secs| secs.checked_mul(INTERVALS_PER_SEC))
        .and_then(|intervals| intervals.checked_add(time.nanos as u64 / 100))
        .filter(|&intervals| intervals != 0 && intervals <= i64::MAX as u64)
        .map(|intervals| FileTime {
            low: intervals as u32,
            high: (intervals >> 32) as u32,
        })
        .ok_or(ErrorKind::InvalidInput.into())
}

/// The permission bits that stand for a set of attributes.
fn mode(attributes: u32) -> u32 {
    let mut mode = if attributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
        0o777
    } else {
        0o666
    };
    if attributes & FILE_ATTRIBUTE_READONLY != 0 {
        mode &= !0o222;
    }
    mode
}

pub(crate) fn handle_metadata(handle: BorrowedHandle<'_>) -> Result<Metadata> {
    // Only files and directories have the information asked below.
    // SAFETY: no memory is involved. The last error is cleared first, to
    // tell a handle of unknown type from a failure.
    let kind = unsafe {
        SetLastError(0);
        GetFileType(handle.as_raw())
    };
    let file_type = match kind {
        FILE_TYPE_DISK => None,
        FILE_TYPE_CHAR => Some(FileType::CharDevice),
        FILE_TYPE_PIPE => Some(FileType::Fifo),
        _ => {
            let error = last_error();
            if error.raw_os_error() != 0 {
                return Err(error);
            }
            Some(FileType::Unknown)
        }
    };
    if let Some(file_type) = file_type {
        return Ok(Metadata {
            file_type,
            len: 0,
            mode: 0o666,
            modified: Timestamp::default(),
            accessed: Timestamp::default(),
            created: None,
            links: 1,
            device: 0,
            inode: 0,
            raw: 0,
            unix: UnixMetadata::default(),
        });
    }

    let mut info = ByHandleFileInformation::default();
    // SAFETY: `info` is the structure the call fills.
    cvt(unsafe { GetFileInformationByHandle(handle.as_raw(), &raw mut info) })?;
    let mut file_type = if info.attributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
        FileType::Directory
    } else {
        FileType::File
    };
    // A reparse point is a link or something else, by its tag. (A handle
    // opened through a link is on what the link points to.)
    if info.attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        let tag = attribute_tag(handle)?;
        if is_link(tag.attributes, tag.reparse_tag) {
            file_type = FileType::Symlink;
        }
    }
    Ok(Metadata {
        file_type,
        len: (info.file_size_high as u64) << 32 | info.file_size_low as u64,
        mode: mode(info.attributes),
        modified: timestamp(info.last_write_time),
        accessed: timestamp(info.last_access_time),
        created: Some(timestamp(info.creation_time)),
        links: info.number_of_links as u64,
        device: info.volume_serial_number as u64,
        inode: (info.file_index_high as u64) << 32 | info.file_index_low as u64,
        raw: info.attributes,
        unix: UnixMetadata::default(),
    })
}

/// Opens what `path` names for something else than its content: a
/// directory will do, and no sharing mode of other handles gets in the way.
fn open_for(path: &[u8], access: u32, follow: bool) -> Result<OwnedHandle> {
    let mut flags = FILE_FLAG_BACKUP_SEMANTICS;
    if !follow {
        flags |= FILE_FLAG_OPEN_REPARSE_POINT;
    }
    with_path(path, |path| create_file(path, access, OPEN_EXISTING, flags))
}

pub(crate) fn metadata(path: &[u8], follow: bool) -> Result<Metadata> {
    // Like `std`: there is no call that describes a path as completely as
    // a handle is described.
    let handle = open_for(path, 0, follow)?;
    handle_metadata(handle.as_handle())
}

pub(crate) fn set_len(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
    let end = len as i64;
    // SAFETY: the information of this class is one `LARGE_INTEGER`.
    cvt(unsafe {
        SetFileInformationByHandle(
            handle.as_raw(),
            FILE_END_OF_FILE_INFO,
            (&raw const end).cast(),
            size_of::<i64>() as u32,
        )
    })
}

pub(crate) fn allocate(handle: BorrowedHandle<'_>, len: u64) -> Result<()> {
    let mut info = FileStandardInfo::default();
    // SAFETY: `info` is the structure of this class, of the size given.
    cvt(unsafe {
        GetFileInformationByHandleEx(
            handle.as_raw(),
            FILE_STANDARD_INFO,
            (&raw mut info).cast(),
            size_of::<FileStandardInfo>() as u32,
        )
    })?;
    let len = len as i64;
    // An allocation smaller than the file would cut the file.
    if len > info.allocation_size {
        // SAFETY: the information of this class is one `LARGE_INTEGER`.
        cvt(unsafe {
            SetFileInformationByHandle(
                handle.as_raw(),
                FILE_ALLOCATION_INFO,
                (&raw const len).cast(),
                size_of::<i64>() as u32,
            )
        })?;
    }
    if len > info.end_of_file {
        set_len(handle, len as u64)?;
    }
    Ok(())
}

pub(crate) fn handle_space(handle: BorrowedHandle<'_>) -> Result<Space> {
    let mut info = FileFsFullSizeInformation::default();
    let mut status_block = IoStatusBlock {
        status: 0,
        information: 0,
    };
    // SAFETY: `info` is the structure of this class, of the size given.
    let status = unsafe {
        NtQueryVolumeInformationFile(
            handle.as_raw(),
            &raw mut status_block,
            (&raw mut info).cast(),
            size_of::<FileFsFullSizeInformation>() as u32,
            FILE_FS_FULL_SIZE_INFORMATION,
        )
    };
    if status < 0 {
        return Err(nt_error(status));
    }
    let unit = (info.sectors_per_unit as u64).saturating_mul(info.bytes_per_sector as u64);
    let bytes = |units: i64| (units.max(0) as u64).saturating_mul(unit);
    Ok(Space {
        total: bytes(info.total_units),
        free: bytes(info.actual_available_units),
        available: bytes(info.caller_available_units),
    })
}

pub(crate) fn space(path: &[u8]) -> Result<Space> {
    // `GetDiskFreeSpaceExW` wants a directory: any file tells as much once
    // it is open.
    let handle = open_for(path, 0, true)?;
    handle_space(handle.as_handle())
}

/// Called by `CopyFileExW` as it copies: notes how much of the main stream
/// of the file has been copied, as `std` does.
unsafe extern "system" fn copy_progress(
    _total_size: i64,
    _total_transferred: i64,
    _stream_size: i64,
    stream_transferred: i64,
    stream: u32,
    _reason: u32,
    _source: *mut c_void,
    _destination: *mut c_void,
    data: *const c_void,
) -> u32 {
    if stream == 1 {
        // SAFETY: `data` is the pointer `copy` gave, to an `i64` that lives
        // until `CopyFileExW` returns.
        unsafe { data.cast_mut().cast::<i64>().write(stream_transferred) };
    }
    // PROGRESS_CONTINUE
    0
}

pub(crate) fn copy(from: &[u8], to: &[u8]) -> Result<u64> {
    let mut copied = 0i64;
    let result = with_path(from, |from| {
        with_path(to, |to| {
            // SAFETY: both paths are NUL-terminated wide strings; the
            // routine is given a pointer to `copied`, which outlives the
            // call.
            cvt(unsafe {
                CopyFileExW(
                    from.as_ptr(),
                    to.as_ptr(),
                    Some(copy_progress),
                    (&raw mut copied).cast_const().cast(),
                    ptr::null_mut(),
                    0,
                )
            })
            .map_err(|error| match error.raw_os_error() {
                // A directory is refused as "access denied": say what the
                // other systems say.
                ERROR_ACCESS_DENIED if is_dir(from) => {
                    Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED)
                }
                error => Error::from_raw_os_error(error),
            })
        })
    });
    match result {
        Ok(()) => Ok(copied.max(0) as u64),
        // A file is not copied to itself: it is in the way of its own
        // opening. Say what the other systems are made to say.
        Err(error) if error.raw_os_error() == ERROR_SHARING_VIOLATION && same_file(from, to) => {
            Err(ErrorKind::InvalidInput.into())
        }
        Err(error) => Err(error),
    }
}

/// Whether the two paths name one file.
fn same_file(a: &[u8], b: &[u8]) -> bool {
    let id = |path: &[u8]| {
        let meta = metadata(path, true).ok()?;
        Some((meta.device, meta.inode))
    };
    id(a).is_some_and(|a| Some(a) == id(b))
}

pub(crate) fn sync(handle: BorrowedHandle<'_>, _data_only: bool) -> Result<()> {
    // SAFETY: no memory is involved.
    cvt(unsafe { FlushFileBuffers(handle.as_raw()) })
}

pub(crate) fn set_handle_permissions(handle: BorrowedHandle<'_>, mode: u32) -> Result<()> {
    let mut info = FileBasicInfo::default();
    let size = size_of::<FileBasicInfo>() as u32;
    // SAFETY: `info` is the structure of this class, of the size given.
    cvt(unsafe {
        GetFileInformationByHandleEx(
            handle.as_raw(),
            FILE_BASIC_INFO,
            (&raw mut info).cast(),
            size,
        )
    })?;
    let mut attributes = info.attributes;
    if mode & 0o222 == 0 {
        attributes |= FILE_ATTRIBUTE_READONLY;
    } else {
        attributes &= !FILE_ATTRIBUTE_READONLY;
    }
    // Zero would mean "leave the attributes": NORMAL is how none is said.
    if attributes == 0 {
        attributes = FILE_ATTRIBUTE_NORMAL;
    }
    // Zero times are left as they are.
    let info = FileBasicInfo {
        attributes,
        ..FileBasicInfo::default()
    };
    // SAFETY: as above.
    cvt(unsafe {
        SetFileInformationByHandle(
            handle.as_raw(),
            FILE_BASIC_INFO,
            (&raw const info).cast(),
            size,
        )
    })
}

pub(crate) fn set_permissions(path: &[u8], mode: u32) -> Result<()> {
    let handle = open_for(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, true)?;
    set_handle_permissions(handle.as_handle(), mode)
}

pub(crate) fn set_handle_times(handle: BorrowedHandle<'_>, times: &FileTimes) -> Result<()> {
    let accessed = times.accessed.map(file_time).transpose()?;
    let modified = times.modified.map(file_time).transpose()?;
    let pointer = |time: &Option<FileTime>| time.as_ref().map_or(ptr::null(), ptr::from_ref);
    // SAFETY: each pointer is null, for a time to leave alone, or points to
    // a `FILETIME` that lives until the call returns.
    cvt(unsafe {
        SetFileTime(
            handle.as_raw(),
            ptr::null(),
            pointer(&accessed),
            pointer(&modified),
        )
    })
}

pub(crate) fn set_times(path: &[u8], times: &FileTimes) -> Result<()> {
    let handle = open_for(path, FILE_WRITE_ATTRIBUTES, true)?;
    set_handle_times(handle.as_handle(), times)
}

pub(crate) fn lock(handle: BorrowedHandle<'_>, kind: LockKind, wait: bool) -> Result<bool> {
    let mut flags = match kind {
        LockKind::Shared => 0,
        LockKind::Exclusive => LOCKFILE_EXCLUSIVE_LOCK,
    };
    if !wait {
        flags |= LOCKFILE_FAIL_IMMEDIATELY;
    }
    // The handle may be open for overlapped operation, without oscall
    // knowing: the call then returns while the lock is still asked for, and
    // the system writes to `overlapped` when the request completes. Give
    // the request an event to signal then, as `std` does. Its low bit says
    // that the completion is not for the completion port the handle may be
    // associated with, where nobody knows of it.
    // SAFETY: an unnamed event with default security, reset by hand.
    let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) };
    if event.is_null() {
        return Err(last_error());
    }
    // SAFETY: the event was just created.
    let event = unsafe { OwnedHandle::from_raw(event) };
    // The whole file: every byte from offset zero.
    let mut overlapped = Overlapped::at(0);
    overlapped.internal = STATUS_PENDING as usize;
    overlapped.event = event.as_raw().map_addr(|addr| addr | 1);
    // SAFETY: `overlapped` is written until the request is complete, which
    // is waited for below before anything else is done.
    let locked = unsafe {
        LockFileEx(
            handle.as_raw(),
            flags,
            0,
            u32::MAX,
            u32::MAX,
            &raw mut overlapped,
        )
    };
    let result = if locked != 0 {
        Ok(())
    } else {
        let error = last_error();
        if error.raw_os_error() == ERROR_IO_PENDING {
            // SAFETY: `overlapped` starts with the status block of the
            // request, pending before the call, and lives; the event is
            // for this request alone.
            let status =
                unsafe { wait_completion(event.as_raw(), true, &raw const overlapped.internal) };
            if status >= 0 {
                Ok(())
            } else {
                Err(nt_error(status))
            }
        } else {
            Err(error)
        }
    };
    match result {
        Ok(()) => Ok(true),
        Err(error) if !wait && error.raw_os_error() == ERROR_LOCK_VIOLATION => Ok(false),
        Err(error) => Err(error),
    }
}

pub(crate) fn unlock(handle: BorrowedHandle<'_>) -> Result<()> {
    // Twice, like `std`: a handle may hold both an exclusive lock and a
    // shared one, and each call releases one of them. Having none to
    // release is not an error on the other systems.
    for _ in 0..2 {
        // SAFETY: no memory is involved.
        match cvt(unsafe { UnlockFile(handle.as_raw(), 0, 0, u32::MAX, u32::MAX) }) {
            Ok(()) => {}
            Err(error) if error.raw_os_error() == ERROR_NOT_LOCKED => break,
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

pub(crate) fn create_dir(path: &[u8], _mode: u32) -> Result<()> {
    with_path(path, |path| {
        // SAFETY: `path` is a NUL-terminated wide string.
        cvt(unsafe { CreateDirectoryW(path.as_ptr(), ptr::null()) })
    })
}

pub(crate) fn remove_dir(path: &[u8]) -> Result<()> {
    with_path(path, |path| {
        // SAFETY: `path` is a NUL-terminated wide string.
        cvt(unsafe { RemoveDirectoryW(path.as_ptr()) })
    })
}

pub(crate) fn remove_file(path: &[u8]) -> Result<()> {
    with_path(path, |path| {
        // SAFETY: `path` is a NUL-terminated wide string.
        let Err(error) = cvt(unsafe { DeleteFileW(path.as_ptr()) }) else {
            return Ok(());
        };
        // A directory is refused as "access denied": say what the other
        // systems say.
        if error.raw_os_error() == ERROR_ACCESS_DENIED && is_dir(path) {
            return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
        }
        Err(error)
    })
}

pub(crate) fn rename(from: &[u8], to: &[u8]) -> Result<()> {
    with_path(from, |from| {
        with_path(to, |to| {
            // SAFETY: both paths are NUL-terminated wide strings.
            cvt(unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), MOVEFILE_REPLACE_EXISTING) })
        })
    })
}

pub(crate) fn hard_link(original: &[u8], link: &[u8]) -> Result<()> {
    with_path(original, |original| {
        with_path(link, |link| {
            // SAFETY: both paths are NUL-terminated wide strings.
            cvt(unsafe { CreateHardLinkW(link.as_ptr(), original.as_ptr(), ptr::null()) })
        })
    })
}

pub(crate) fn is_separator(c: u8) -> bool {
    c == b'\\' || c == b'/'
}

/// Whether the target of a link to be created at `link` is a directory
/// right now. A relative target is relative to where the link is.
fn target_is_dir(target: &[u8], link: &[u8]) -> bool {
    let query = |path: &[u8]| with_path(path, |path| Ok(is_dir(path))).unwrap_or(false);
    // Rooted (`\dir`, `\\server\share`) or with a drive (`C:\dir`, `C:dir`):
    // the place of the link does not matter.
    let absolute = target.first().is_some_and(|&c| is_separator(c)) || target.get(1) == Some(&b':');
    if absolute {
        return query(target);
    }
    // The directory of the link: up to its last separator, or to its drive.
    let parent = match link.iter().rposition(|&c| is_separator(c)) {
        Some(at) => &link[..=at],
        None if link.get(1) == Some(&b':') => &link[..2],
        None => &[],
    };
    let len = parent.len() + target.len();
    let mut stack = [0u8; 1024];
    if let Some(joined) = stack.get_mut(..len) {
        joined[..parent.len()].copy_from_slice(parent);
        joined[parent.len()..].copy_from_slice(target);
        return query(joined);
    }
    #[cfg(feature = "alloc")]
    {
        let mut joined = alloc::vec::Vec::new();
        if joined.try_reserve_exact(len).is_ok() {
            joined.extend_from_slice(parent);
            joined.extend_from_slice(target);
            return query(&joined);
        }
    }
    false
}

pub(crate) fn symlink(target: &[u8], link: &[u8]) -> Result<()> {
    let mut flags = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
    if target_is_dir(target, link) {
        flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
    }
    with_wide(target, |target| {
        with_path(link, |link| {
            // SAFETY: both paths are NUL-terminated wide strings.
            let create =
                |flags| unsafe { CreateSymbolicLinkW(link.as_ptr(), target.as_ptr(), flags) };
            if create(flags) != 0 {
                return Ok(());
            }
            let error = last_error();
            // Windows before 10.0.15063 does not know the flag that lets
            // the developer mode create links: try without it.
            if error.raw_os_error() == ERROR_INVALID_PARAMETER
                && create(flags & !SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) != 0
            {
                return Ok(());
            }
            Err(error)
        })
    })
}

/// Converts a wide string from the system to WTF-8 in the caller's buffer.
fn to_wtf8(wide: &[u16], buf: &mut [u8]) -> Result<usize> {
    wide_to_wtf8(wide, buf).ok_or(ErrorKind::BufferTooSmall.into())
}

pub(crate) fn read_link(path: &[u8], buf: &mut [u8]) -> Result<usize> {
    let handle = open_for(path, 0, false)?;
    read_link_of(handle.as_handle(), buf)
}

/// Reads the target of the link `handle` is open on.
fn read_link_of(handle: BorrowedHandle<'_>, buf: &mut [u8]) -> Result<usize> {
    // `REPARSE_DATA_BUFFER`, read as 16-bit units: the tag (two units), the
    // length of the data and a reserved field (one each), then for a link
    // the offset and length in bytes of the substitute name and of the
    // print name (one each), flags (two units, symbolic links only), and
    // the buffer the names are in.
    let mut data = [0u16; MAXIMUM_REPARSE_DATA_BUFFER_SIZE / 2];
    let mut returned = 0;
    // SAFETY: `data` is writable for the size given, which is the largest
    // a reparse point can be. Both callers opened `handle` themselves, for
    // synchronous operation: the call returns when the operation is
    // complete.
    let result = cvt(unsafe {
        DeviceIoControl(
            handle.as_raw(),
            FSCTL_GET_REPARSE_POINT,
            ptr::null(),
            0,
            data.as_mut_ptr().cast(),
            MAXIMUM_REPARSE_DATA_BUFFER_SIZE as u32,
            &raw mut returned,
            ptr::null_mut(),
        )
    });
    let not_a_link = || Error::from(ErrorKind::InvalidInput);
    match result {
        Ok(()) => {}
        Err(error) if error.raw_os_error() == ERROR_NOT_A_REPARSE_POINT => {
            return Err(not_a_link());
        }
        Err(error) => return Err(error),
    }
    let tag = data[0] as u32 | (data[1] as u32) << 16;
    let (names, relative) = match tag {
        IO_REPARSE_TAG_SYMLINK => {
            let flags = data[8] as u32 | (data[9] as u32) << 16;
            (10, flags & SYMLINK_FLAG_RELATIVE != 0)
        }
        IO_REPARSE_TAG_MOUNT_POINT => (8, false),
        _ => return Err(not_a_link()),
    };
    let start = names + data[4] as usize / 2;
    let end = start + data[5] as usize / 2;
    let mut target = data.get(start..end).ok_or(Error::from(ErrorKind::Other))?;
    // An absolute target is in the form of the object manager: `\??\C:\dir`.
    const NT_PREFIX: [u16; 4] = [b'\\' as u16, b'?' as u16, b'?' as u16, b'\\' as u16];
    if !relative && let Some(rest) = target.strip_prefix(&NT_PREFIX) {
        target = rest;
    }
    to_wtf8(target, buf)
}

/// Runs one of the calls that write a path to a wide buffer and return its
/// length, or the size they need when the buffer is too small.
fn wide_path(buf: &mut [u8], mut call: impl FnMut(*mut u16, u32) -> u32) -> Result<usize> {
    let mut stack = [0u16; 1024];
    let len = call(stack.as_mut_ptr(), stack.len() as u32) as usize;
    if len == 0 {
        return Err(last_error());
    }
    if len < stack.len() {
        return to_wtf8(&stack[..len], buf);
    }
    #[cfg(feature = "alloc")]
    {
        let mut needed = len;
        // The path may grow between two calls: a few rounds, not a loop.
        for _ in 0..4 {
            let mut heap = alloc::vec::Vec::new();
            heap.try_reserve_exact(needed)
                .map_err(|_| ErrorKind::OutOfMemory)?;
            heap.resize(needed, 0u16);
            let len = call(heap.as_mut_ptr(), heap.len().min(u32::MAX as usize) as u32) as usize;
            if len == 0 {
                return Err(last_error());
            }
            if len < heap.len() {
                return to_wtf8(&heap[..len], buf);
            }
            needed = len + 1;
        }
    }
    // As for the paths given to oscall: long ones need `alloc`.
    Err(ErrorKind::InvalidFilename.into())
}

pub(crate) fn canonicalize(path: &[u8], buf: &mut [u8]) -> Result<usize> {
    let handle = open_for(path, 0, true)?;
    // SAFETY: the pointer and the length are those of a writable buffer.
    wide_path(buf, |path, len| unsafe {
        // Zero: the normalised name with its drive letter (VOLUME_NAME_DOS).
        GetFinalPathNameByHandleW(handle.as_raw(), path, len, 0)
    })
}

pub(crate) fn current_dir(buf: &mut [u8]) -> Result<usize> {
    // SAFETY: the pointer and the length are those of a writable buffer.
    wide_path(buf, |path, len| unsafe { GetCurrentDirectoryW(len, path) })
}

pub(crate) fn set_current_dir(path: &[u8]) -> Result<()> {
    with_wide(path, |path| {
        // SAFETY: `path` is a NUL-terminated wide string.
        cvt(unsafe { SetCurrentDirectoryW(path.as_ptr()) })
    })
}

/// The size of the buffer the system fills with entries.
const DIR_BUF: usize = 4096;
/// The longest name of an entry, in UTF-16 units.
const NAME_MAX: usize = 255;
/// `offsetof(FILE_ID_BOTH_DIR_INFO, FileName)`. Before it, the fields used
/// here: `NextEntryOffset` (at 0), `FileAttributes` (56), `FileNameLength`
/// in bytes (60), `EaSize` (64), which is the reparse tag of a reparse
/// point, and `FileId` (96).
const DIR_INFO_NAME: usize = 104;

/// The system wants the buffer aligned for the structure it writes.
#[repr(C, align(8))]
struct DirBuf([u8; DIR_BUF]);

pub(crate) struct Dir {
    handle: OwnedHandle,
    buf: DirBuf,
    /// Where the next entry starts in `buf`, if it holds one.
    pos: Option<usize>,
    /// The name of the current entry, converted to WTF-8.
    name: [u8; NAME_MAX * 3],
}

impl Dir {
    pub(crate) fn new(handle: OwnedHandle) -> Self {
        Self {
            handle,
            buf: DirBuf([0; DIR_BUF]),
            pos: None,
            name: [0; NAME_MAX * 3],
        }
    }

    pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
        self.handle.as_handle()
    }

    pub(crate) fn name(&self, entry: &RawDirEntry) -> &[u8] {
        &self.name[entry.name.0..entry.name.1]
    }

    pub(crate) fn next(&mut self) -> Result<Option<RawDirEntry>> {
        let pos = match self.pos {
            Some(pos) => pos,
            None => {
                // Not `GetFileInformationByHandleEx`, which is this call:
                // the handle may be open for overlapped operation, as it
                // can come from anywhere (`Dir::from_handle`), and the
                // call then returns before the system has written the
                // entries. `completed` waits for that.
                let mut block = IoStatusBlock::PENDING;
                // SAFETY: `buf` is writable for its size and aligned for
                // the structures of this class; it and `block` are written
                // until the operation is complete, which is waited for.
                let (status, _) = unsafe {
                    let status = NtQueryDirectoryFile(
                        self.handle.as_raw(),
                        ptr::null_mut(),
                        ptr::null(),
                        ptr::null(),
                        &raw mut block,
                        self.buf.0.as_mut_ptr().cast(),
                        DIR_BUF as u32,
                        FILE_ID_BOTH_DIRECTORY_INFORMATION,
                        0,
                        ptr::null(),
                        0,
                    );
                    completed(self.handle.as_handle(), status, &raw const block)
                };
                if status < 0 {
                    let error = nt_error(status);
                    if error.raw_os_error() == ERROR_NO_MORE_FILES {
                        return Ok(None);
                    }
                    return Err(error);
                }
                0
            }
        };
        // What the system wrote is not trusted to be well formed.
        let malformed = || Error::from(ErrorKind::Other);
        self.pos = None;
        let entry = self.buf.0.get(pos..).ok_or_else(malformed)?;
        let u32_at = |at: usize| {
            entry
                .get(at..at + 4)
                .and_then(|bytes| bytes.try_into().ok())
                .map(u32::from_le_bytes)
                .ok_or_else(malformed)
        };
        let next = u32_at(0)? as usize;
        let attributes = u32_at(56)?;
        let name_len = u32_at(60)? as usize;
        let reparse_tag = u32_at(64)?;
        let inode = u32_at(96)? as u64 | (u32_at(100)? as u64) << 32;
        let name = entry
            .get(DIR_INFO_NAME..DIR_INFO_NAME + name_len)
            .ok_or_else(malformed)?;
        if next != 0 {
            self.pos = Some(pos + next);
        }

        let mut wide = [0u16; NAME_MAX];
        let units = name_len / 2;
        let wide = wide.get_mut(..units).ok_or(ErrorKind::InvalidFilename)?;
        for (unit, bytes) in wide.iter_mut().zip(name.as_chunks::<2>().0) {
            *unit = u16::from_le_bytes(*bytes);
        }
        let len = wide_to_wtf8(wide, &mut self.name).ok_or(ErrorKind::InvalidFilename)?;
        Ok(Some(RawDirEntry {
            name: (0, len),
            file_type: Some(if is_link(attributes, reparse_tag) {
                FileType::Symlink
            } else if attributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
                FileType::Directory
            } else {
                FileType::File
            }),
            inode,
        }))
    }
}

// Directory-relative operations. Win32 has none: they are made with the
// calls Win32 itself is built on, which take a root directory next to the
// name. The name is then the kernel's business alone: `\` is the only
// separator, and `.` and `..` are names like any other.

/// The error for an `NTSTATUS`.
fn nt_error(status: i32) -> Error {
    // Win32 turns this one into "access denied": say what the other systems
    // say, as `open` does.
    if status == STATUS_FILE_IS_A_DIRECTORY {
        return Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED);
    }
    crate::sys::nt_error(status)
}

/// Calls `f` with `path` as the kernel wants a relative name: in UTF-16,
/// with `\` between its components and no `.` component. The second
/// argument says whether the path asks for a directory, by ending with a
/// separator or with `.`. The name is empty when the path is the directory
/// it is relative to, which only some callers can do something with
/// (`or_self`).
fn with_nt_name<R>(
    path: &[u8],
    or_self: bool,
    f: impl FnOnce(&[u16], bool) -> Result<R>,
) -> Result<R> {
    const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
    // The longest name a `UNICODE_STRING` holds, in units.
    const MAX: usize = 0x7fff;

    // A drive would make the kernel look for a stream of a file.
    if path.get(1) == Some(&b':') {
        return Err(ErrorKind::InvalidInput.into());
    }
    with_wide(path, |wide| {
        // Without the NUL: the kernel counts.
        let wide = &wide[..wide.len() - 1];
        let mut stack = [0u16; 512];
        #[cfg(feature = "alloc")]
        let mut heap = alloc::vec::Vec::new();
        let name = match stack.get_mut(..wide.len()) {
            Some(name) => name,
            #[cfg(feature = "alloc")]
            None => {
                heap.try_reserve_exact(wide.len())
                    .map_err(|_| ErrorKind::OutOfMemory)?;
                heap.resize(wide.len(), 0u16);
                &mut heap[..]
            }
            #[cfg(not(feature = "alloc"))]
            None => return Err(ErrorKind::InvalidFilename.into()),
        };
        let mut len = 0;
        let mut directory = false;
        for component in wide.split(|c| SEPARATORS.contains(c)) {
            // Whatever comes last decides.
            directory = matches!(component, [] | [0x2e]);
            if directory {
                continue;
            }
            if len > 0 {
                name[len] = SEPARATORS[0];
                len += 1;
            }
            name[len..len + component.len()].copy_from_slice(component);
            len += component.len();
        }
        if len == 0 && !or_self {
            return Err(ErrorKind::InvalidInput.into());
        }
        if len > MAX {
            return Err(ErrorKind::InvalidFilename.into());
        }
        f(&name[..len], directory)
    })
}

/// `NtCreateFile` on `name` in the directory `root`, with every sharing
/// mode and no inheritance. Returns the handle and what was done to get it
/// (`FILE_OPENED`, `FILE_CREATED`...).
fn nt_create(
    root: BorrowedHandle<'_>,
    name: &[u16],
    access: u32,
    disposition: u32,
    options: u32,
) -> Result<(OwnedHandle, usize)> {
    let name = UnicodeString {
        len: (name.len() * 2) as u16,
        capacity: (name.len() * 2) as u16,
        buf: name.as_ptr(),
    };
    // Names are compared as Win32 compares them. Without OBJ_INHERIT the
    // handle is not inheritable.
    let attributes = ObjectAttributes {
        len: size_of::<ObjectAttributes>() as u32,
        root: root.as_raw(),
        name: &raw const name,
        attributes: OBJ_CASE_INSENSITIVE,
        security_descriptor: ptr::null(),
        security_qos: ptr::null(),
    };
    let mut handle = ptr::null_mut();
    let mut status_block = IoStatusBlock {
        status: 0,
        information: 0,
    };
    // SAFETY: the structures are those the call reads and writes, and the
    // name they point to lives until it returns.
    let status = unsafe {
        NtCreateFile(
            &raw mut handle,
            access,
            &raw const attributes,
            &raw mut status_block,
            ptr::null(),
            FILE_ATTRIBUTE_NORMAL,
            FILE_SHARE_ALL,
            disposition,
            options | FILE_SYNCHRONOUS_IO_NONALERT,
            ptr::null(),
            0,
        )
    };
    if status < 0 {
        return Err(nt_error(status));
    }
    // SAFETY: the handle was just created.
    Ok((
        unsafe { OwnedHandle::from_raw(handle) },
        status_block.information,
    ))
}

/// What `open_in` is to find.
#[derive(Clone, Copy, PartialEq)]
enum Want {
    Anything,
    NotADirectory,
    Directory,
}

/// Opens what `path` names in the directory `dir`, for something else than
/// its content.
fn open_in(
    dir: BorrowedHandle<'_>,
    path: &[u8],
    or_self: bool,
    access: u32,
    follow: bool,
    want: Want,
) -> Result<OwnedHandle> {
    with_nt_name(path, or_self, |name, directory| {
        let mut options = FILE_OPEN_FOR_BACKUP_INTENT;
        if !follow {
            options |= FILE_OPEN_REPARSE_POINT;
        }
        match (want, directory) {
            (Want::Directory, _) | (Want::Anything, true) => options |= FILE_DIRECTORY_FILE,
            (Want::Anything, false) => {}
            (Want::NotADirectory, false) => options |= FILE_NON_DIRECTORY_FILE,
            (Want::NotADirectory, true) => {
                // `file/`: not a directory if it is a file, and a directory
                // if it is not.
                let access = FILE_READ_ATTRIBUTES | SYNCHRONIZE;
                nt_create(dir, name, access, FILE_OPEN, options | FILE_DIRECTORY_FILE)?;
                return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
            }
        }
        let (handle, _) = nt_create(dir, name, access | SYNCHRONIZE, FILE_OPEN, options)?;
        Ok(handle)
    })
}

pub(crate) fn open_at(
    dir: BorrowedHandle<'_>,
    path: &[u8],
    options: &OpenOptions,
) -> Result<OwnedHandle> {
    // As in `open`, in the kernel's words. Win32 adds the two other rights
    // to every open.
    let mut access = SYNCHRONIZE | FILE_READ_ATTRIBUTES;
    if options.read {
        access |= GENERIC_READ;
    }
    if options.append {
        access |= FILE_GENERIC_WRITE & !FILE_WRITE_DATA;
    } else if options.write {
        access |= GENERIC_WRITE;
    }
    let creates = options.create || options.create_new;
    let truncate_existing = options.create && options.truncate && !options.create_new;
    let disposition = if options.create_new {
        FILE_CREATE
    } else {
        match (options.create, options.truncate) {
            (false, false) => FILE_OPEN,
            (false, true) => FILE_OVERWRITE,
            (true, _) => FILE_OPEN_IF,
        }
    };
    let mut flags = if options.directory {
        FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT
    } else {
        FILE_NON_DIRECTORY_FILE
    };
    if options.no_follow || options.create_new {
        flags |= FILE_OPEN_REPARSE_POINT;
    }

    with_nt_name(path, true, |name, directory| {
        if directory && !options.directory {
            // `name/` is a directory or nothing, and a directory is not
            // opened without being asked for.
            if !creates {
                let access = FILE_READ_ATTRIBUTES | SYNCHRONIZE;
                let flags = FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT;
                nt_create(dir, name, access, FILE_OPEN, flags)?;
            }
            return Err(Error::from_raw_os_error(ERROR_DIRECTORY_NOT_SUPPORTED));
        }
        let (handle, done) = nt_create(dir, name, access, disposition, flags)?;
        if truncate_existing && done == FILE_OPENED {
            set_len(handle.as_handle(), 0)?;
        }
        if options.no_follow {
            let info = attribute_tag(handle.as_handle())?;
            if is_link(info.attributes, info.reparse_tag) {
                return Err(Error::from_raw_os_error(ERROR_CANT_RESOLVE_FILENAME));
            }
        }
        Ok(handle)
    })
}

pub(crate) fn metadata_at(dir: BorrowedHandle<'_>, path: &[u8], follow: bool) -> Result<Metadata> {
    let handle = open_in(
        dir,
        path,
        true,
        FILE_READ_ATTRIBUTES,
        follow,
        Want::Anything,
    )?;
    handle_metadata(handle.as_handle())
}

pub(crate) fn set_permissions_at(dir: BorrowedHandle<'_>, path: &[u8], mode: u32) -> Result<()> {
    let access = FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES;
    let handle = open_in(dir, path, true, access, true, Want::Anything)?;
    set_handle_permissions(handle.as_handle(), mode)
}

pub(crate) fn set_times_at(dir: BorrowedHandle<'_>, path: &[u8], times: &FileTimes) -> Result<()> {
    let handle = open_in(dir, path, true, FILE_WRITE_ATTRIBUTES, true, Want::Anything)?;
    set_handle_times(handle.as_handle(), times)
}

pub(crate) fn create_dir_at(dir: BorrowedHandle<'_>, path: &[u8], _mode: u32) -> Result<()> {
    with_nt_name(path, false, |name, _| {
        // What `CreateDirectoryW` does.
        let options = FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT | FILE_OPEN_REPARSE_POINT;
        let access = FILE_LIST_DIRECTORY | SYNCHRONIZE;
        nt_create(dir, name, access, FILE_CREATE, options)?;
        Ok(())
    })
}

/// Removes what `handle`, opened with the right to delete, is open on: now
/// if the system can, when the last handle to it is closed otherwise.
fn delete(handle: BorrowedHandle<'_>) -> Result<()> {
    // As `DeleteFileW` and `RemoveDirectoryW` do on the systems that have
    // it: the name goes away at once, even if the file is open elsewhere.
    let flags = FILE_DISPOSITION_DELETE | FILE_DISPOSITION_POSIX_SEMANTICS;
    // SAFETY: the information of this class is one `ULONG` of flags.
    let result = cvt(unsafe {
        SetFileInformationByHandle(
            handle.as_raw(),
            FILE_DISPOSITION_INFO_EX,
            (&raw const flags).cast(),
            size_of::<u32>() as u32,
        )
    });
    match result {
        // Windows before 10.0.17134, or a filesystem that is not NTFS.
        Err(error)
            if matches!(
                error.raw_os_error(),
                ERROR_INVALID_PARAMETER | ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED
            ) => {}
        result => return result,
    }
    let delete = 1u8;
    // SAFETY: the information of this class is one `BOOLEAN`.
    cvt(unsafe {
        SetFileInformationByHandle(
            handle.as_raw(),
            FILE_DISPOSITION_INFO,
            (&raw const delete).cast(),
            size_of::<u8>() as u32,
        )
    })
}

pub(crate) fn remove_dir_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
    let handle = open_in(dir, path, false, DELETE, false, Want::Directory)?;
    delete(handle.as_handle())
}

pub(crate) fn remove_file_at(dir: BorrowedHandle<'_>, path: &[u8]) -> Result<()> {
    let handle = open_in(dir, path, false, DELETE, false, Want::NotADirectory)?;
    delete(handle.as_handle())
}

/// Gives the file `handle` is open on the name `name` in the directory
/// `root`: as its only name (`FILE_RENAME_INFORMATION`) or as one more
/// (`FILE_LINK_INFORMATION`). The two structures are the same.
fn set_name(
    handle: BorrowedHandle<'_>,
    class: i32,
    replace: bool,
    root: BorrowedHandle<'_>,
    name: &[u16],
) -> Result<()> {
    const STACK: usize = 512;
    #[repr(C)]
    struct Info {
        // A `BOOLEAN`, in a union with 32 bits of flags.
        replace: u32,
        root: *mut c_void,
        // In bytes.
        len: u32,
        name: [u16; STACK],
    }
    const HEADER: usize = core::mem::offset_of!(Info, name);

    let call = |info: *const c_void, size: usize| {
        let mut status_block = IoStatusBlock {
            status: 0,
            information: 0,
        };
        // SAFETY: `info` is the structure of this class, readable for
        // `size` bytes.
        let status = unsafe {
            NtSetInformationFile(
                handle.as_raw(),
                &raw mut status_block,
                info,
                size as u32,
                class,
            )
        };
        if status < 0 {
            return Err(nt_error(status));
        }
        Ok(())
    };
    if name.len() <= STACK {
        let mut info = Info {
            replace: replace as u32,
            root: root.as_raw(),
            len: (name.len() * 2) as u32,
            name: [0; STACK],
        };
        info.name[..name.len()].copy_from_slice(name);
        // The system wants at least the structure with a name of one unit,
        // padding included.
        let size = (HEADER + name.len() * 2).max(HEADER + 4);
        return call((&raw const info).cast(), size);
    }
    #[cfg(feature = "alloc")]
    {
        // 64-bit units, to be aligned for the structure.
        let size = HEADER + name.len() * 2;
        let mut buf = alloc::vec::Vec::<u64>::new();
        buf.try_reserve_exact(size.div_ceil(8))
            .map_err(|_| ErrorKind::OutOfMemory)?;
        buf.resize(size.div_ceil(8), 0);
        let info = buf.as_mut_ptr().cast::<Info>();
        // SAFETY: the buffer is aligned for `Info` and holds its header and
        // `name.len()` units after it; only those are written, through
        // pointers, as the buffer is shorter than an `Info`.
        unsafe {
            (&raw mut (*info).replace).write(replace as u32);
            (&raw mut (*info).root).write(root.as_raw());
            (&raw mut (*info).len).write((name.len() * 2) as u32);
            (&raw mut (*info).name)
                .cast::<u16>()
                .copy_from_nonoverlapping(name.as_ptr(), name.len());
        }
        call(info.cast_const().cast(), size)
    }
    #[cfg(not(feature = "alloc"))]
    Err(ErrorKind::InvalidFilename.into())
}

pub(crate) fn rename_at(
    from_dir: BorrowedHandle<'_>,
    from: &[u8],
    to_dir: BorrowedHandle<'_>,
    to: &[u8],
) -> Result<()> {
    // What `MoveFileExW` does with `MOVEFILE_REPLACE_EXISTING`.
    let handle = open_in(from_dir, from, false, DELETE, false, Want::Anything)?;
    with_nt_name(to, false, |to, _| {
        set_name(
            handle.as_handle(),
            FILE_RENAME_INFORMATION,
            true,
            to_dir,
            to,
        )
    })
}

pub(crate) fn hard_link_at(
    original_dir: BorrowedHandle<'_>,
    original: &[u8],
    link_dir: BorrowedHandle<'_>,
    link: &[u8],
) -> Result<()> {
    // What `CreateHardLinkW` does.
    let access = FILE_WRITE_ATTRIBUTES;
    let handle = open_in(original_dir, original, false, access, false, Want::Anything)?;
    with_nt_name(link, false, |link, _| {
        set_name(
            handle.as_handle(),
            FILE_LINK_INFORMATION,
            false,
            link_dir,
            link,
        )
    })
}

pub(crate) fn read_link_at(dir: BorrowedHandle<'_>, path: &[u8], buf: &mut [u8]) -> Result<usize> {
    let handle = open_in(dir, path, true, FILE_READ_ATTRIBUTES, false, Want::Anything)?;
    read_link_of(handle.as_handle(), buf)
}

/// Appends the directory of `link` and then `target` to `buf[..base]`, less
/// what `.` and `..` cancel, which the kernel does not know: each component
/// that remains with a `\` in front. `None` if `..` leads above the base,
/// or if the result does not fit.
fn join_target(buf: &mut [u16], base: usize, link: &[u16], target: &[u16]) -> Option<usize> {
    const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
    const DOT: u16 = b'.' as u16;

    let parent = match link.iter().rposition(|&c| c == SEPARATORS[0]) {
        Some(at) => &link[..at],
        None => &[],
    };
    let mut len = base;
    for component in parent
        .split(|&c| c == SEPARATORS[0])
        .chain(target.split(|c| SEPARATORS.contains(c)))
    {
        match component {
            [] | [DOT] => {}
            [DOT, DOT] => {
                if len == base && base == 0 {
                    return None;
                }
                len = buf[..len].iter().rposition(|&c| c == SEPARATORS[0])?;
            }
            _ => {
                let room = buf.get_mut(len..len + 1 + component.len())?;
                room[0] = SEPARATORS[0];
                room[1..].copy_from_slice(component);
                len += room.len();
            }
        }
    }
    Some(len)
}

/// Whether `target`, the relative target of a link to be created as `link`
/// in the directory `dir`, is a directory right now.
fn relative_target_is_dir(dir: BorrowedHandle<'_>, link: &[u16], target: &[u16]) -> bool {
    let mut joined = [0u16; 1024];
    if let Some(len) = join_target(&mut joined, 0, link, target) {
        // Under `dir`: looked at from it. The first separator is not part
        // of a relative name.
        let name = joined[..len].get(1..).unwrap_or(&[]);
        let access = FILE_READ_ATTRIBUTES | SYNCHRONIZE;
        let options = FILE_DIRECTORY_FILE | FILE_OPEN_FOR_BACKUP_INTENT;
        return nt_create(dir, name, access, FILE_OPEN, options).is_ok();
    }
    // Above `dir`, which only a path can tell: the one `dir` has now.
    // SAFETY: the pointer and the length are those of a writable buffer.
    let base = unsafe {
        GetFinalPathNameByHandleW(dir.as_raw(), joined.as_mut_ptr(), joined.len() as u32, 0)
    } as usize;
    if base == 0 || base >= joined.len() {
        return false;
    }
    match join_target(&mut joined, base, link, target) {
        // With the NUL that ends it.
        Some(len) if len < joined.len() => {
            joined[len] = 0;
            is_dir(&joined[..=len])
        }
        _ => false,
    }
}

pub(crate) fn symlink_at(target: &[u8], dir: BorrowedHandle<'_>, link: &[u8]) -> Result<()> {
    const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
    // `\??\`, which starts an absolute path for the kernel, and `UNC\`,
    // which follows it for a path on a server.
    const NT_PREFIX: [u16; 4] = [b'\\' as u16, b'?' as u16, b'?' as u16, b'\\' as u16];
    const UNC: [u16; 4] = [b'U' as u16, b'N' as u16, b'C' as u16, b'\\' as u16];
    // `REPARSE_DATA_BUFFER` in 16-bit units, as in `read_link_of`: the
    // header takes 4 units, the offsets and the flags 6, and the two names
    // follow.
    const HEADER: usize = 4;
    const NAMES: usize = 10;

    let mut data = [0u16; MAXIMUM_REPARSE_DATA_BUFFER_SIZE / 2];
    let too_long = || Error::from(ErrorKind::InvalidFilename);
    with_nt_name(link, false, |link, _| {
        // The reparse data and whether the link is one to a directory.
        let (len, directory) = with_wide(target, |wide| {
            let target = &wide[..wide.len() - 1];
            let is = |at: usize, c: u8| target.get(at) == Some(&(c as u16));
            let separator = |at: usize| target.get(at).is_some_and(|c| SEPARATORS.contains(c));
            // What Win32 calls relative, for a link: no drive, and at most
            // one separator in front (the root of the drive the link is
            // on).
            let relative = !is(1, b':') && !(separator(0) && separator(1));
            let names = &mut data[NAMES..];
            let (substitute, print, directory);
            if relative {
                // The same name twice.
                let len = target.len();
                let both = names.get_mut(..2 * len).ok_or_else(too_long)?;
                both[..len].copy_from_slice(target);
                both[len..].copy_from_slice(target);
                (substitute, print) = ((0, len), (len, len));
                directory = if separator(0) {
                    is_dir(wide)
                } else {
                    relative_target_is_dir(dir, link, target)
                };
            } else {
                // The substitute name is the full path as the kernel takes
                // it, and the print name the full path as Win32 does. Room
                // is left in front of the latter for the prefix that makes
                // it the former: `\\server\share` gains the most, six units
                // (`\??\UNC\server\share`).
                const ROOM: usize = 6;
                let room = names.len() / 2;
                // SAFETY: `wide` is a NUL-terminated wide string, and the
                // buffer is writable for the length given.
                let full = unsafe {
                    GetFullPathNameW(
                        wide.as_ptr(),
                        (room - ROOM) as u32,
                        names[ROOM..].as_mut_ptr(),
                        ptr::null_mut(),
                    )
                } as usize;
                if full == 0 {
                    return Err(last_error());
                }
                if full >= room - ROOM {
                    return Err(too_long());
                }
                let path = ROOM..ROOM + full;
                let at = |i: usize, c: u8| names[ROOM + i] == c as u16;
                // What of the path follows the kernel's prefix, and what
                // comes in between.
                let (skip, middle): (usize, &[u16]) =
                    if full >= 4 && at(0, b'\\') && at(1, b'\\') && at(3, b'\\') {
                        if at(2, b'?') || at(2, b'.') {
                            // `\\?\C:\dir`, `\\.\device`.
                            (4, &[])
                        } else {
                            (2, &UNC)
                        }
                    } else if full >= 2 && at(0, b'\\') && at(1, b'\\') {
                        (2, &UNC)
                    } else {
                        (0, &[])
                    };
                let rest = full - skip;
                let substitute_len = NT_PREFIX.len() + middle.len() + rest;
                let start = path.end;
                let end = start + substitute_len;
                if end > names.len() {
                    return Err(too_long());
                }
                names[start..start + 4].copy_from_slice(&NT_PREFIX);
                names[start + 4..start + 4 + middle.len()].copy_from_slice(middle);
                names.copy_within(path.start + skip..path.end, start + 4 + middle.len());
                (substitute, print) = ((start, substitute_len), (path.start, full));
                directory = is_dir(wide);
            }
            let end = substitute.0 + substitute.1;
            let end = end.max(print.0 + print.1);
            // Offsets and lengths are in bytes, from the first name.
            let bytes = |units: usize| (units * 2) as u16;
            let flags = if relative { SYMLINK_FLAG_RELATIVE } else { 0 }
                | SYMLINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
            data[0] = IO_REPARSE_TAG_SYMLINK as u16;
            data[1] = (IO_REPARSE_TAG_SYMLINK >> 16) as u16;
            data[2] = bytes(NAMES - HEADER + end);
            data[3] = 0;
            data[4] = bytes(substitute.0);
            data[5] = bytes(substitute.1);
            data[6] = bytes(print.0);
            data[7] = bytes(print.1);
            data[8] = flags as u16;
            data[9] = (flags >> 16) as u16;
            Ok((NAMES + end, directory))
        })?;

        // A link is an empty file, or an empty directory, with the data
        // that says where it leads.
        let options = FILE_OPEN_REPARSE_POINT
            | FILE_OPEN_FOR_BACKUP_INTENT
            | if directory {
                FILE_DIRECTORY_FILE
            } else {
                FILE_NON_DIRECTORY_FILE
            };
        let access = FILE_WRITE_ATTRIBUTES | DELETE | SYNCHRONIZE;
        let (handle, _) = nt_create(dir, link, access, FILE_CREATE, options)?;
        let set = |data: &[u16]| {
            let mut returned = 0;
            // SAFETY: `data` is readable for the size given. `handle` was
            // opened above for synchronous operation (`nt_create`): the
            // call returns when the operation is complete.
            cvt(unsafe {
                DeviceIoControl(
                    handle.as_raw(),
                    FSCTL_SET_REPARSE_POINT,
                    data.as_ptr().cast(),
                    (len * 2) as u32,
                    ptr::null_mut(),
                    0,
                    &raw mut returned,
                    ptr::null_mut(),
                )
            })
        };
        let mut result = set(&data);
        // As in `symlink`: Windows before 10.0.15063 does not know the flag
        // that lets the developer mode create links.
        if result.is_err_and(|error| error.raw_os_error() == ERROR_INVALID_PARAMETER) {
            data[8] &= !(SYMLINK_FLAG_ALLOW_UNPRIVILEGED_CREATE as u16);
            if set(&data).is_ok() {
                result = Ok(());
            }
        }
        if result.is_err() {
            // Not a link: nothing is left behind.
            let _ = delete(handle.as_handle());
        }
        result
    })
}