syd 3.42.0

rock-solid application kernel
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
//
// Syd: rock-solid application kernel
// src/compat.rs: Compatibility code for different libcs
//
// Copyright (c) 2023, 2024, 2025 Ali Polatel <alip@chesswob.org>
// waitid and WaitStatus are based in part upon nix which is:
//     Copyright (c) nix authors
//     SPDX-License-Identifier: MIT
//
// SPDX-License-Identifier: GPL-3.0

#![allow(non_camel_case_types)]

use std::{
    alloc::{alloc, dealloc, Layout},
    cell::RefCell,
    cmp::Ordering,
    os::fd::{AsFd, AsRawFd, RawFd},
    ptr::NonNull,
    sync::LazyLock,
};

use bitflags::bitflags;
use libseccomp::ScmpSyscall;
use memchr::arch::all::is_equal;
use nix::{
    errno::Errno,
    fcntl::{AtFlags, OFlag},
    sys::{
        epoll::EpollOp,
        socket::SockaddrLike,
        wait::{Id, WaitPidFlag, WaitStatus as NixWaitStatus},
    },
    unistd::Pid,
    NixPath,
};
use serde::{ser::SerializeMap, Serialize, Serializer};

use crate::{config::*, fs::FileType, XPath};

// x32 compatibility
// See https://sourceware.org/bugzilla/show_bug.cgi?id=16437
#[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))]
#[expect(non_camel_case_types)]
pub(crate) type timespec_tv_nsec_t = i64;
#[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))]
#[expect(non_camel_case_types)]
pub(crate) type timespec_tv_nsec_t = libc::c_long;

// C-compatible layout of the `timespec64` structure.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(C)]
pub(crate) struct TimeSpec64 {
    pub(crate) tv_sec: i64,
    pub(crate) tv_nsec: i64,
}

// C-compatible layout of the `timespec32` structure.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(C)]
pub(crate) struct TimeSpec32 {
    pub(crate) tv_sec: i32,
    pub(crate) tv_nsec: i32,
}

/// Aligns the given length to the nearest 4-byte boundary.
///
/// This function is useful for ensuring that data structures in a 32-bit architecture
/// are correctly aligned to 4 bytes as required by many system interfaces for proper operation.
///
/// # Arguments
///
/// * `len` - The length that needs to be aligned.
///
/// # Returns
///
/// The smallest length that is a multiple of 4 bytes and is not less than `len`.
pub(crate) const fn cmsg_align_32(len: usize) -> usize {
    len.saturating_add(3) & !3
}

/// Calculates the total space required for a control message including data and padding on a 32-bit system.
///
/// This function is specifically tailored for 32-bit architectures where control message
/// headers and data need to be aligned to 4-byte boundaries.
///
/// # Arguments
///
/// * `length` - The length of the data in the control message.
///
/// # Returns
///
/// The total space in bytes required to store the control message, ensuring proper alignment.
pub(crate) const fn cmsg_space_32(length: u32) -> usize {
    cmsg_align_32((length as usize).saturating_add(cmsg_align_32(std::mem::size_of::<cmsghdr32>())))
}

/// Computes the byte length of a control message's header and data for a 32-bit system.
///
/// This function helps in determining the correct length for control messages where the
/// header and data must be aligned to 4-byte boundaries in a 32-bit architecture.
///
/// # Arguments
///
/// * `length` - The length of the data part of the control message.
///
/// # Returns
///
/// The combined length of the control message header and the data, aligned as required.
pub(crate) const fn cmsg_len_32(length: u32) -> usize {
    cmsg_align_32(std::mem::size_of::<cmsghdr32>()).saturating_add(length as usize)
}

/// This structure represents the Linux 32-bit data structure 'struct stat'
#[repr(C)]
pub struct stat32 {
    /// Device ID.
    pub st_dev: libc::dev_t,

    /// Inode number (32-bit).
    pub st_ino: u32,

    /// Number of hard links.
    pub st_nlink: libc::nlink_t,

    /// File mode.
    pub st_mode: libc::mode_t,

    /// User ID of owner.
    pub st_uid: libc::uid_t,

    /// Group ID of owner.
    pub st_gid: libc::gid_t,

    /// Padding.
    __pad0: libc::c_int,

    /// Device ID (if special file).
    pub st_rdev: libc::dev_t,

    /// Total size, in bytes (32-bit).
    pub st_size: i32,

    /// Block size for filesystem I/O.
    pub st_blksize: libc::blksize_t,

    /// Number of 512B blocks allocated (32-bit).
    pub st_blocks: i32,

    /// Time of last access (32-bit).
    pub st_atime: i32,

    /// Nanoseconds of last access (32-bit).
    pub st_atime_nsec: i32,

    /// Time of last modification (32-bit).
    pub st_mtime: i32,

    /// Nanoseconds of last modification (32-bit).
    pub st_mtime_nsec: i32,

    /// Time of last status change (32-bit).
    pub st_ctime: i32,

    /// Nanoseconds of last status change (32-bit).
    pub st_ctime_nsec: i32,

    /// Reserved for future use (32-bit).
    __unused: [i32; 3],
}

impl From<libc::stat64> for stat32 {
    #[expect(clippy::cast_possible_truncation)]
    #[expect(clippy::unnecessary_cast)]
    fn from(stat: libc::stat64) -> Self {
        Self {
            st_dev: stat.st_dev as u64,
            st_ino: stat.st_ino as u32,
            st_nlink: stat.st_nlink,
            st_mode: stat.st_mode,
            st_uid: stat.st_uid,
            st_gid: stat.st_gid,
            __pad0: 0,
            st_rdev: stat.st_rdev as u64,
            st_size: stat.st_size as i32,
            st_blksize: stat.st_blksize,
            st_blocks: stat.st_blocks as i32,
            st_atime: stat.st_atime as i32,
            st_atime_nsec: stat.st_atime_nsec as i32,
            st_mtime: stat.st_mtime as i32,
            st_mtime_nsec: stat.st_mtime_nsec as i32,
            st_ctime: stat.st_ctime as i32,
            st_ctime_nsec: stat.st_ctime_nsec as i32,
            __unused: [0; 3],
        }
    }
}

/// This structure represents the Linux 32-bit data structure 'struct iovec'
#[derive(Copy, Clone)]
#[repr(C)]
pub struct iovec32 {
    iov_base: u32,
    iov_len: u32,
}

impl From<iovec32> for libc::iovec {
    fn from(src: iovec32) -> Self {
        libc::iovec {
            iov_base: src.iov_base as *mut _,
            iov_len: src.iov_len as usize,
        }
    }
}

/// This structure represents the Linux 32-bit data structure 'struct mmmsghdr'
#[derive(Copy, Clone)]
#[repr(C)]
pub struct mmsghdr32 {
    pub msg_hdr: msghdr32,
    pub msg_len: u32,
}

/// This structure represents the Linux native data structure 'struct mmsghdr'
#[derive(Copy, Clone)]
#[repr(C)]
pub struct mmsghdr {
    pub msg_hdr: msghdr,
    pub msg_len: libc::c_uint,
}

impl From<mmsghdr32> for mmsghdr {
    fn from(src: mmsghdr32) -> Self {
        mmsghdr {
            msg_hdr: msghdr::from(src.msg_hdr),
            msg_len: src.msg_len,
        }
    }
}

impl From<mmsghdr> for mmsghdr32 {
    fn from(src: mmsghdr) -> Self {
        mmsghdr32 {
            msg_hdr: msghdr32::from(src.msg_hdr),
            msg_len: src.msg_len,
        }
    }
}

const _: () = {
    assert!(
        size_of::<libc::mmsghdr>() == size_of::<mmsghdr>(),
        "Size mismatch between libc::mmsghdr and compat::mmsghdr"
    );
};

impl From<libc::mmsghdr> for mmsghdr {
    fn from(msg: libc::mmsghdr) -> Self {
        // SAFETY: Since we have confirmed the sizes are the same at compile time,
        // we can safely perform a transmute. This assumes no differences in alignment
        // or memory layout between libc::mmsghdr and mmsghdr.
        unsafe { std::mem::transmute(msg) }
    }
}

impl From<libc::mmsghdr> for mmsghdr32 {
    fn from(msg: libc::mmsghdr) -> Self {
        mmsghdr::from(msg).into()
    }
}

impl From<mmsghdr> for libc::mmsghdr {
    fn from(msg: mmsghdr) -> Self {
        // SAFETY: Since we have confirmed the sizes are the same at compile time,
        // we can safely perform a transmute. This assumes no differences in alignment
        // or memory layout between libc::mmsghdr and mmsghdr.
        unsafe { std::mem::transmute(msg) }
    }
}

impl From<mmsghdr32> for libc::mmsghdr {
    fn from(msg: mmsghdr32) -> Self {
        mmsghdr::from(msg).into()
    }
}

/// This union represents the Linux data structure 'struct mmsghdr'
#[repr(C)]
pub union mmsghdr_union {
    // 32-bit mmsghdr32
    pub m32: mmsghdr32,
    // Native mmsghdr
    pub m64: mmsghdr,
}

/// This structure represents the Linux 32-bit data structure 'struct cmsghdr'
#[repr(C)]
pub struct cmsghdr32 {
    pub cmsg_len: u32,
    pub cmsg_level: i32,
    pub cmsg_type: i32,
}

/// This structure represents the Linux native data structure 'struct cmsghdr'
#[repr(C)]
pub struct cmsghdr {
    pub cmsg_len: libc::size_t,
    pub cmsg_level: libc::c_int,
    pub cmsg_type: libc::c_int,
}

impl From<cmsghdr32> for cmsghdr {
    fn from(src: cmsghdr32) -> Self {
        cmsghdr {
            cmsg_len: src.cmsg_len as libc::size_t,
            cmsg_level: src.cmsg_level,
            cmsg_type: src.cmsg_type,
        }
    }
}

/// This structure represents the Linux 32-bit data structure 'struct msghdr'
#[derive(Copy, Clone)]
#[repr(C)]
pub struct msghdr32 {
    // In 32-bit systems, pointers are 32-bit.
    pub msg_name: u32,       // Use u32 to represent a 32-bit pointer.
    pub msg_namelen: u32,    // socklen_t is typically 32-bit.
    pub msg_iov: u32,        // Use u32 to represent a 32-bit pointer to iovec.
    pub msg_iovlen: u32,     // size_t is 32-bit on 32-bit systems.
    pub msg_control: u32,    // Use u32 to represent a 32-bit pointer.
    pub msg_controllen: u32, // size_t is 32-bit on 32-bit systems.
    pub msg_flags: i32,      // c_int remains the same (32-bit).
}

/// This structure represents the Linux native data structure 'struct msghdr'
#[derive(Copy, Clone)]
#[repr(C)]
pub struct msghdr {
    pub msg_name: *mut libc::c_void,
    pub msg_namelen: libc::socklen_t,
    pub msg_iov: *mut libc::iovec,
    pub msg_iovlen: libc::size_t,
    pub msg_control: *mut libc::c_void,
    pub msg_controllen: libc::size_t,
    pub msg_flags: libc::c_int,
}

impl From<msghdr32> for msghdr {
    fn from(msg: msghdr32) -> Self {
        msghdr {
            msg_name: msg.msg_name as *mut libc::c_void,
            msg_namelen: msg.msg_namelen as libc::socklen_t,
            msg_iov: msg.msg_iov as *mut libc::iovec,
            msg_iovlen: msg.msg_iovlen as libc::size_t,
            msg_control: msg.msg_control as *mut libc::c_void,
            msg_controllen: msg.msg_controllen as libc::size_t,
            msg_flags: msg.msg_flags as libc::c_int,
        }
    }
}

#[expect(clippy::unnecessary_cast)]
#[expect(clippy::cast_possible_truncation)]
impl From<msghdr> for msghdr32 {
    fn from(msg: msghdr) -> Self {
        msghdr32 {
            msg_name: msg.msg_name as u32,
            msg_namelen: msg.msg_namelen as u32,
            msg_iov: msg.msg_iov as u32,
            msg_iovlen: msg.msg_iovlen as u32,
            msg_control: msg.msg_control as u32,
            msg_controllen: msg.msg_controllen as u32,
            msg_flags: msg.msg_flags as i32,
        }
    }
}

const _: () = {
    assert!(
        size_of::<libc::msghdr>() == size_of::<msghdr>(),
        "Size mismatch between libc::msghdr and compat::msghdr"
    );
};

impl From<libc::msghdr> for msghdr {
    fn from(msg: libc::msghdr) -> Self {
        // SAFETY: Since we have confirmed the sizes are the same at compile time,
        // we can safely perform a transmute. This assumes no differences in alignment
        // or memory layout between libc::msghdr and msghdr.
        unsafe { std::mem::transmute(msg) }
    }
}

impl From<libc::msghdr> for msghdr32 {
    fn from(msg: libc::msghdr) -> Self {
        msghdr::from(msg).into()
    }
}

/// Rust equivalent of the Linux kernel's struct xattr_args:
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct XattrArgs {
    /// 64-bit pointer to user buffer.
    pub value: u64,

    /// Size of the buffer.
    pub size: u32,

    /// XATTR_ flags (e.g., XATTR_CREATE or XATTR_REPLACE). Should be 0
    /// for getxattrat(2).
    pub flags: u32,
}

// Note getxattrat may not be available,
// and libc::SYS_getxattrat may not be defined.
// Therefore we query the number using libseccomp.
static SYS_GETXATTRAT: LazyLock<libc::c_long> = LazyLock::new(|| {
    ScmpSyscall::from_name("getxattrat")
        .map(i32::from)
        .map(libc::c_long::from)
        .unwrap_or(0)
});

/// Safe getxattrat(2) wrapper which is new in Linux>=6.13.
///
/// # Safety
///
/// This function dereferences `name` argument which is a raw pointer.
/// It is safe for this pointer to be NULL but otherwise it must point
/// to valid memory and the caller must ensure that.
pub unsafe fn getxattrat<Fd: AsFd, P: ?Sized + NixPath>(
    dirfd: Fd,
    path: &P,
    name: *const libc::c_char,
    args: &mut XattrArgs,
    flags: AtFlags,
) -> Result<usize, Errno> {
    let sysno = if *SYS_GETXATTRAT > 0 {
        *SYS_GETXATTRAT
    } else {
        return Err(Errno::ENOSYS);
    };

    path.with_nix_path(|c_path| {
        #[expect(clippy::cast_possible_truncation)]
        #[expect(clippy::cast_sign_loss)]
        Errno::result(
            // SAFETY: In libc we trust.
            unsafe {
                libc::syscall(
                    sysno as libc::c_long,
                    dirfd.as_fd().as_raw_fd(),
                    c_path.as_ptr(),
                    flags.bits(),
                    name,
                    args as *mut XattrArgs,
                    std::mem::size_of::<XattrArgs>(),
                )
            },
        )
        .map(|r| r as usize)
    })?
}

// Note setxattrat may not be available,
// and libc::SYS_setxattrat may not be defined.
// Therefore we query the number using libseccomp.
static SYS_SETXATTRAT: LazyLock<libc::c_long> = LazyLock::new(|| {
    ScmpSyscall::from_name("setxattrat")
        .map(i32::from)
        .map(libc::c_long::from)
        .unwrap_or(0)
});

/// Safe setxattrat(2) wrapper which is new in Linux>=6.13.
///
/// # Safety
///
/// This function dereferences `name` argument which is a raw pointer.
/// It is safe for this pointer to be NULL but otherwise it must point
/// to valid memory and the caller must ensure that.
pub unsafe fn setxattrat<Fd: AsFd, P: ?Sized + NixPath>(
    dirfd: Fd,
    path: &P,
    name: *const libc::c_char,
    args: &XattrArgs,
    flags: AtFlags,
) -> Result<(), Errno> {
    let sysno = if *SYS_SETXATTRAT > 0 {
        *SYS_SETXATTRAT
    } else {
        return Err(Errno::ENOSYS);
    };

    path.with_nix_path(|c_path| {
        // SAFETY: In libc we trust.
        Errno::result(unsafe {
            libc::syscall(
                sysno as libc::c_long,
                dirfd.as_fd().as_raw_fd(),
                c_path.as_ptr(),
                flags.bits(),
                name,
                args as *const XattrArgs,
                std::mem::size_of::<XattrArgs>(),
            )
        })
        .map(drop)
    })?
}

// Note listxattrat may not be available,
// and libc::SYS_listxattrat may not be defined.
// Therefore we query the number using libseccomp.
static SYS_LISTXATTRAT: LazyLock<libc::c_long> = LazyLock::new(|| {
    ScmpSyscall::from_name("listxattrat")
        .map(i32::from)
        .map(libc::c_long::from)
        .unwrap_or(0)
});

/// Safe listxattrat(2) wrapper which is new in Linux>=6.13.
///
/// # Safety
///
/// This function dereferences `addr` argument which is a raw pointer.
/// It is safe for this pointer to be NULL but otherwise it must point
/// to valid memory and the caller must ensure that.
pub unsafe fn listxattrat<Fd: AsFd, P: ?Sized + NixPath>(
    dirfd: Fd,
    path: &P,
    flags: AtFlags,
    addr: *mut libc::c_char,
    size: usize,
) -> Result<usize, Errno> {
    let sysno = if *SYS_LISTXATTRAT > 0 {
        *SYS_LISTXATTRAT
    } else {
        return Err(Errno::ENOSYS);
    };

    path.with_nix_path(|c_path| {
        #[expect(clippy::cast_possible_truncation)]
        #[expect(clippy::cast_sign_loss)]
        Errno::result(
            // SAFETY: In libc we trust.
            unsafe {
                libc::syscall(
                    sysno as libc::c_long,
                    dirfd.as_fd().as_raw_fd(),
                    c_path.as_ptr(),
                    flags.bits(),
                    addr,
                    size,
                )
            },
        )
        .map(|r| r as usize)
    })?
}

// Note removexattrat may not be available,
// and libc::SYS_removexattrat may not be defined.
// Therefore we query the number using libseccomp.
static SYS_REMOVEXATTRAT: LazyLock<libc::c_long> = LazyLock::new(|| {
    ScmpSyscall::from_name("removexattrat")
        .map(i32::from)
        .map(libc::c_long::from)
        .unwrap_or(0)
});

/// Safe removexattrat(2) wrapper, new in Linux>=6.13.
///
/// # Safety
///
/// This function dereferences `name` argument which is a raw pointer.
/// It is safe for this pointer to be NULL but otherwise it must point
/// to valid memory and the caller must ensure that.
pub unsafe fn removexattrat<Fd: AsFd, P: ?Sized + NixPath>(
    dirfd: Fd,
    path: &P,
    name: *const libc::c_char,
    flags: AtFlags,
) -> Result<(), Errno> {
    let sysno = if *SYS_REMOVEXATTRAT > 0 {
        *SYS_REMOVEXATTRAT
    } else {
        return Err(Errno::ENOSYS);
    };

    path.with_nix_path(|c_path| {
        // SAFETY: In libc we trust.
        Errno::result(unsafe {
            libc::syscall(
                sysno as libc::c_long,
                dirfd.as_fd().as_raw_fd(),
                c_path.as_ptr(),
                flags.bits(),
                name,
            )
        })
        .map(drop)
    })?
}

/// This structure represents the Linux data structure `struct statx_timestamp`
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
pub struct FileStatxTimestamp {
    pub tv_sec: i64,
    pub tv_nsec: u32,
    __statx_timestamp_pad1: [i32; 1],
}

impl PartialEq for FileStatxTimestamp {
    fn eq(&self, other: &Self) -> bool {
        self.tv_sec == other.tv_sec && self.tv_nsec == other.tv_nsec
    }
}

impl Eq for FileStatxTimestamp {}

impl PartialOrd for FileStatxTimestamp {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for FileStatxTimestamp {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.tv_sec.cmp(&other.tv_sec) {
            Ordering::Equal => self.tv_nsec.cmp(&other.tv_nsec),
            ord => ord,
        }
    }
}

impl Serialize for FileStatxTimestamp {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(2))?;

        map.serialize_entry("sec", &self.tv_sec)?;
        map.serialize_entry("nsec", &self.tv_nsec)?;

        map.end()
    }
}

/// This structure represents the Linux data structure `struct statx`
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct FileStatx {
    pub stx_mask: u32,   // What results were written [uncond]
    stx_blksize: u32,    // Preferred general I/O size [uncond]
    stx_attributes: u64, // Flags conveying information about the file [uncond]

    pub stx_nlink: u32, // Number of hard links
    pub stx_uid: u32,   // User ID of owner
    pub stx_gid: u32,   // Group ID of owner
    pub stx_mode: u16,  // File mode
    __statx_pad1: [u16; 1],

    pub stx_ino: u64,         // Inode number
    pub stx_size: u64,        // File size
    stx_blocks: u64,          // Number of 512-byte blocks allocated
    stx_attributes_mask: u64, // Mask to show what's supported in stx_attributes

    pub stx_atime: FileStatxTimestamp, // Last access time
    stx_btime: FileStatxTimestamp,     // File creation time
    pub stx_ctime: FileStatxTimestamp, // Last attribute change time
    pub stx_mtime: FileStatxTimestamp, // Last data modification time

    pub stx_rdev_major: u32, // Device ID of special file [if bdev/cdev]
    pub stx_rdev_minor: u32,

    // Note, these are not not public on purpose
    // as they return inconsistent values on filesystems
    // such as btrfs and overlayfs. `stx_mnt_id` should
    // be used instead.
    pub(crate) stx_dev_major: u32, // ID of device containing file [uncond]
    pub(crate) stx_dev_minor: u32,

    pub stx_mnt_id: u64,
    stx_dio_mem_align: u32,    // Memory buffer alignment for direct I/O
    stx_dio_offset_align: u32, // File offset alignment for direct I/O

    stx_subvol: u64, // Subvolume identifier

    stx_atomic_write_unit_min: u32, // Min atomic write unit in bytes
    stx_atomic_write_unit_max: u32, // Max atomic write unit in bytes
    stx_atomic_write_segments_max: u32, // Max atomic write segment count

    stx_dio_read_offset_align: u32, // File offset alignment for direct I/O reads

    stx_atomic_write_unit_max_opt: u32, // Optimised max atomic write unit in bytes
    __statx_spare2: [u32; 1],

    __statx_spare3: [u64; 8], // Spare space for future expansion
}

impl FileStatx {
    pub(crate) fn file_mode(&self) -> libc::mode_t {
        libc::mode_t::from(self.stx_mode) & !libc::S_IFMT
    }

    pub(crate) fn file_type(&self) -> FileType {
        FileType::from(libc::mode_t::from(self.stx_mode))
    }
}

impl Serialize for FileStatx {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(15))?;

        map.serialize_entry("mask", &self.stx_mask)?;
        map.serialize_entry("nlink", &self.stx_nlink)?;
        map.serialize_entry("uid", &self.stx_uid)?;
        map.serialize_entry("gid", &self.stx_gid)?;
        map.serialize_entry("mode", &self.stx_mode)?;
        map.serialize_entry("file_mode", &self.file_mode())?;
        map.serialize_entry("file_type", &self.file_type())?;
        map.serialize_entry("ino", &self.stx_ino)?;
        map.serialize_entry("size", &self.stx_size)?;
        map.serialize_entry("atime", &self.stx_atime)?;
        map.serialize_entry("ctime", &self.stx_ctime)?;
        map.serialize_entry("mtime", &self.stx_mtime)?;
        map.serialize_entry("rdev_major", &self.stx_rdev_major)?;
        map.serialize_entry("rdev_minor", &self.stx_rdev_minor)?;
        map.serialize_entry("mnt_id", &self.stx_mnt_id)?;

        map.end()
    }
}

/// An iterator over directory entries obtained via the `getdents64`
/// system call.
///
/// This iterator yields `DirEntry` instances by reading from a
/// directory file descriptor.
///
/// # Safety
///
/// This struct uses unsafe code to interact with the `getdents64`
/// system call and to parse the resulting buffer into `dirent64`
/// structures. It manages the allocation and deallocation of the buffer
/// used for reading directory entries.
#[derive(Clone)]
pub struct DirIter {
    buffer: NonNull<u8>,
    bufsiz: usize,
    memsiz: usize,
    offset: usize,
}

const DIRENT_ALIGN: usize = std::mem::align_of::<libc::dirent64>();

impl DirIter {
    /// Creates a new `DirIter` with an allocated buffer of `bufsiz` bytes.
    ///
    /// This buffer is allocated once and reused across directory reads.
    ///
    /// # Parameters
    ///
    /// - `bufsiz`: Size of the buffer, must be properly aligned.
    ///
    /// # Errors
    ///
    /// - `Err(Errno::EINVAL)` for invalid layout.
    /// - `Err::(Errno::ENOMEM)` for allocation failure.
    pub fn new(bufsiz: usize) -> Result<Self, Errno> {
        // Create layout with proper alignment.
        let layout = Layout::from_size_align(bufsiz, DIRENT_ALIGN).or(Err(Errno::EINVAL))?;

        // SAFETY: Allocate buffer with proper alignment and size.
        let buffer = unsafe { alloc(layout) };
        let buffer = NonNull::new(buffer).ok_or(Errno::ENOMEM)?;

        Ok(Self {
            buffer,
            memsiz: bufsiz,
            bufsiz: 0,
            offset: 0,
        })
    }

    /// Read directory entries from the given file descriptor into the
    /// existing buffer.
    ///
    /// Reuses the buffer without additional allocations. Uses the
    /// smaller of provided size or buffer size.
    ///
    /// # Errors
    ///
    /// Returns `Errno` if syscall fails or EOF reached.
    /// EOF is indicated by `Errno::ECANCELED`.
    pub fn readdir<Fd: AsFd>(&mut self, fd: Fd, read_bufsiz: usize) -> Result<&mut Self, Errno> {
        self.offset = 0;
        let bufsiz = read_bufsiz.min(self.memsiz);

        let retsiz = sys_getdents64(fd, self.buffer.as_ptr().cast(), bufsiz)?;
        if retsiz == 0 {
            return Err(Errno::ECANCELED); // EOF or empty directory
        }

        self.bufsiz = retsiz;
        Ok(self)
    }
}

impl<'a> Iterator for &'a mut DirIter {
    type Item = DirEntry<'a>;

    #[expect(clippy::arithmetic_side_effects)]
    fn next(&mut self) -> Option<Self::Item> {
        if self.offset >= self.bufsiz {
            return None;
        }

        // SAFETY: Parse the next dirent safely by borrowing from the buffer.
        unsafe {
            #[expect(clippy::cast_ptr_alignment)]
            let dirent_ptr = self
                .buffer
                .as_ptr()
                .add(self.offset)
                .cast::<libc::dirent64>();
            let d_reclen = (*dirent_ptr).d_reclen as usize;

            // Calculate the name length safely.
            let namelen = libc::strlen((*dirent_ptr).d_name.as_ptr());

            // Borrow the bytes of the `dirent64` structure from the buffer.
            let dirent = std::slice::from_raw_parts(dirent_ptr.cast::<u8>(), d_reclen);

            self.offset += d_reclen;
            Some(DirEntry { dirent, namelen })
        }
    }
}

impl Drop for DirIter {
    fn drop(&mut self) {
        #[expect(clippy::disallowed_methods)]
        let layout = Layout::from_size_align(self.memsiz, DIRENT_ALIGN).unwrap();

        // SAFETY: Deallocate buffer.
        unsafe { dealloc(self.buffer.as_ptr(), layout) };
    }
}

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

/// This struct represents a directory entry.
#[derive(Clone)]
pub struct DirEntry<'a> {
    // The `dirent64` structure.
    dirent: &'a [u8],

    // Size of the file name, in bytes.
    namelen: usize,
}

impl std::fmt::Debug for DirEntry<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("DirEntry")
            .field(&self.as_xpath())
            .field(&self.file_type())
            .finish()
    }
}

impl DirEntry<'_> {
    /// Return an `XPath` representing the name of the directory entry.
    pub fn as_xpath(&self) -> &XPath {
        XPath::from_bytes(self.name_bytes())
    }

    /// Returns the raw bytes of the `dirent64` structure.
    pub fn as_bytes(&self) -> &[u8] {
        self.dirent
    }

    /// Returns true if this is a dot entry.
    /// The special dot entries are `.` and `..`
    pub fn is_dot(&self) -> bool {
        if !self.is_dir() {
            return false;
        }
        let name = self.name_bytes();
        is_equal(name, b"..") || is_equal(name, b".")
    }

    /// Returns true if this is a directory entry.
    pub fn is_dir(&self) -> bool {
        self.file_type().is_dir()
    }

    /// Returns true if this is a regular file entry.
    pub fn is_file(&self) -> bool {
        self.file_type().is_file()
    }

    /// Returns true if this is a symbolic link entry.
    pub fn is_symlink(&self) -> bool {
        self.file_type().is_symlink()
    }

    /// Returns true if this is a block device entry.
    pub fn is_block_device(&self) -> bool {
        self.file_type().is_block_device()
    }

    /// Returns true if this is a character device entry.
    pub fn is_char_device(&self) -> bool {
        self.file_type().is_char_device()
    }

    /// Returns true if this is a FIFO entry.
    pub fn is_fifo(&self) -> bool {
        self.file_type().is_fifo()
    }

    /// Returns true if this is a socket entry.
    pub fn is_socket(&self) -> bool {
        self.file_type().is_socket()
    }

    /// Returns true if this is an unknown entry.
    pub fn is_unknown(&self) -> bool {
        self.file_type().is_unknown()
    }

    /// Returns the file type of the directory entry.
    ///
    /// The return value corresponds to one of the `DT_*` constants defined in `dirent.h`.
    ///
    /// # Safety
    ///
    /// This function assumes that `self.dirent` points to a valid `dirent64` structure,
    /// and that the `d_type` field is accessible without causing undefined behavior.
    pub fn file_type(&self) -> FileType {
        let dirent = self.dirent64();

        // SAFETY: We trust self.dirent points to a valid `dirent64` structure.
        FileType::from(unsafe { (*dirent).d_type })
    }

    /// Return the inode of this `DirEntry`.
    pub fn ino(&self) -> u64 {
        let dirent = self.dirent64();

        // SAFETY: We trust self.dirent points to a valid `dirent64` structure.
        unsafe { (*dirent).d_ino }
    }

    /// Return the size of this `DirEntry`.
    pub fn size(&self) -> usize {
        let dirent = self.dirent64();

        // SAFETY: We trust self.dirent points to a valid `dirent64` structure.
        unsafe { (*dirent).d_reclen as usize }
    }

    /// Return a byte slice of the entry name.
    pub fn name_bytes(&self) -> &[u8] {
        let dirent = self.dirent64();

        // SAFETY: We trust self.dirent points to a valid `dirent64` structure.
        unsafe {
            let d_name = (*dirent).d_name.as_ptr() as *const u8;
            std::slice::from_raw_parts(d_name, self.namelen)
        }
    }

    fn dirent64(&self) -> *const libc::dirent64 {
        // SAFETY: We trust self.dirent points to a valid `dirent64` structure.
        #![allow(clippy::cast_ptr_alignment)]
        self.dirent.as_ptr() as *const libc::dirent64
    }
}

/// Retrieve directory entries from an open directory file descriptor.
///
/// This function returns an iterator over `DirEntry` instances.
///
/// Internally, a thread-local buffer is lazily initialized and reused
/// to avoid repeated memory allocations.
///
/// # Parameters
///
/// - `fd`: The open directory file descriptor.
/// - `bufsiz`: The maximum number of bytes to read into the buffer.
///   If greater than internal buffer size, internal size is used.
///
/// # Returns
///
/// - `Ok`: An iterator over directory entries (`DirEntry`).
/// - `Err`: `Errno` if syscall or allocation errors occur.
///
/// # Safety
///
/// Internally calls the unsafe _getdents64_(2) syscall.
/// The provided file descriptor must be a valid, open directory descriptor.
pub fn getdents64<Fd: AsFd>(
    fd: Fd,
    bufsiz: usize,
) -> Result<impl Iterator<Item = DirEntry<'static>>, Errno> {
    thread_local! {
        static DIR_ITER: RefCell<Option<DirIter>> = const { RefCell::new(None) };
    }

    let iter: &'static mut DirIter = DIR_ITER.with(|cell| {
        // Lazily allocate DirIter with default buffer size.
        let mut borrow = cell.borrow_mut();
        if borrow.is_none() {
            *borrow = Some(DirIter::new(DIRENT_BUF_SIZE)?);
        }

        // SAFETY:
        // 1. We ensured borrow is `Some`.
        // 2. 'static is fine here because the buffer is thread-local
        //    and lives at least as long as the thread.
        let iter: &'static mut DirIter = unsafe {
            std::mem::transmute::<&mut DirIter, &'static mut DirIter>(
                borrow.as_mut().unwrap_unchecked(),
            )
        };

        Ok::<&'static mut DirIter, Errno>(iter)
    })?;

    // Call actual getdents with pre-allocated buffer.
    // Returns ECANCELED on EOF or empty directory.
    iter.readdir(fd, bufsiz)?;

    // Return directory iterator.
    Ok(iter)
}

/// Wrapper for the `getdents64` syscall.
#[expect(clippy::cast_possible_truncation)]
#[expect(clippy::cast_sign_loss)]
fn sys_getdents64<Fd: AsFd>(fd: Fd, buf: *mut libc::c_void, bytes: usize) -> Result<usize, Errno> {
    // SAFETY: In kernel, we trust.
    Errno::result(unsafe {
        libc::syscall(libc::SYS_getdents64, fd.as_fd().as_raw_fd(), buf, bytes)
    })
    .map(|size| size as usize)
}

/// WaitStatus with support for signals that nix' Signal type don't support.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum WaitStatus {
    Exited(Pid, i32),
    Signaled(Pid, i32, bool),
    Stopped(Pid, i32),
    PtraceEvent(Pid, i32, libc::c_int),
    PtraceSyscall(Pid),
    Continued(Pid),
    StillAlive,
}

impl From<NixWaitStatus> for WaitStatus {
    fn from(status: NixWaitStatus) -> Self {
        match status {
            NixWaitStatus::Exited(pid, code) => WaitStatus::Exited(pid, code),
            NixWaitStatus::Signaled(pid, signal, core_dump) => {
                WaitStatus::Signaled(pid, signal as i32, core_dump)
            }
            NixWaitStatus::Stopped(pid, signal) => WaitStatus::Stopped(pid, signal as i32),
            NixWaitStatus::PtraceEvent(pid, signal, event) => {
                WaitStatus::PtraceEvent(pid, signal as i32, event)
            }
            NixWaitStatus::PtraceSyscall(pid) => WaitStatus::PtraceSyscall(pid),
            NixWaitStatus::Continued(pid) => WaitStatus::Continued(pid),
            NixWaitStatus::StillAlive => WaitStatus::StillAlive,
        }
    }
}

fn exited(status: i32) -> bool {
    libc::WIFEXITED(status)
}

fn exit_status(status: i32) -> i32 {
    libc::WEXITSTATUS(status)
}

fn signaled(status: i32) -> bool {
    libc::WIFSIGNALED(status)
}

fn term_signal(status: i32) -> i32 {
    libc::WTERMSIG(status)
}

fn dumped_core(status: i32) -> bool {
    libc::WCOREDUMP(status)
}

fn stopped(status: i32) -> bool {
    libc::WIFSTOPPED(status)
}

fn stop_signal(status: i32) -> i32 {
    libc::WSTOPSIG(status)
}

fn syscall_stop(status: i32) -> bool {
    // From ptrace(2), setting PTRACE_O_TRACESYSGOOD has the effect
    // of delivering SIGTRAP | 0x80 as the signal number for syscall
    // stops. This allows easily distinguishing syscall stops from
    // genuine SIGTRAP signals.
    libc::WSTOPSIG(status) == libc::SIGTRAP | 0x80
}

fn stop_additional(status: i32) -> libc::c_int {
    (status >> 16) as libc::c_int
}

fn continued(status: i32) -> bool {
    libc::WIFCONTINUED(status)
}

impl WaitStatus {
    pub(crate) fn from_raw(pid: Pid, status: i32) -> WaitStatus {
        if exited(status) {
            WaitStatus::Exited(pid, exit_status(status))
        } else if signaled(status) {
            WaitStatus::Signaled(pid, term_signal(status), dumped_core(status))
        } else if stopped(status) {
            let status_additional = stop_additional(status);
            if syscall_stop(status) {
                WaitStatus::PtraceSyscall(pid)
            } else if status_additional == 0 {
                WaitStatus::Stopped(pid, stop_signal(status))
            } else {
                WaitStatus::PtraceEvent(pid, stop_signal(status), stop_additional(status))
            }
        } else {
            assert!(continued(status));
            WaitStatus::Continued(pid)
        }
    }
}

/// Wrapper for the `waitid` syscall
/// This is identical to nix' waitid except we use our custom WaitStatus.
pub fn waitid(id: Id, flags: WaitPidFlag) -> Result<WaitStatus, Errno> {
    #[expect(clippy::cast_sign_loss)]
    let (idtype, idval) = match id {
        Id::All => (libc::P_ALL, 0),
        Id::Pid(pid) => (libc::P_PID, pid.as_raw() as libc::id_t),
        Id::PGid(pid) => (libc::P_PGID, pid.as_raw() as libc::id_t),
        Id::PIDFd(fd) => (libc::P_PIDFD, fd.as_raw_fd() as libc::id_t),
        _ => unreachable!(),
    };

    // SAFETY: In libc, we trust.
    let siginfo = unsafe {
        // Memory is zeroed rather than uninitialized, as not all platforms
        // initialize the memory in the StillAlive case
        let mut siginfo: libc::siginfo_t = std::mem::zeroed();
        Errno::result(libc::waitid(idtype, idval, &raw mut siginfo, flags.bits()))?;
        siginfo
    };

    // SAFETY: In libc, we trust.
    let si_pid = unsafe { siginfo.si_pid() };
    if si_pid == 0 {
        return Ok(WaitStatus::StillAlive);
    }

    assert_eq!(siginfo.si_signo, libc::SIGCHLD);

    let pid = Pid::from_raw(si_pid);
    // SAFETY: In libc, we trust.
    let si_status = unsafe { siginfo.si_status() };

    let status = match siginfo.si_code {
        libc::CLD_EXITED => WaitStatus::Exited(pid, si_status),
        libc::CLD_KILLED | libc::CLD_DUMPED => {
            WaitStatus::Signaled(pid, si_status, siginfo.si_code == libc::CLD_DUMPED)
        }
        libc::CLD_STOPPED => WaitStatus::Stopped(pid, si_status),
        libc::CLD_CONTINUED => WaitStatus::Continued(pid),
        libc::CLD_TRAPPED => {
            if si_status == libc::SIGTRAP | 0x80 {
                WaitStatus::PtraceSyscall(pid)
            } else {
                WaitStatus::PtraceEvent(pid, si_status & 0xff, (si_status >> 8) as libc::c_int)
            }
        }
        _ => return Err(Errno::EINVAL),
    };

    Ok(status)
}

pub(crate) fn pipe2_raw(flags: OFlag) -> Result<(RawFd, RawFd), Errno> {
    let mut fds = std::mem::MaybeUninit::<[RawFd; 2]>::uninit();

    // SAFETY: We use this when nix' version which returns an OwnedFd
    // does not work for our purposes e.g. in mini-threads spawned
    // by network syscall handlers.
    let res = unsafe { libc::pipe2(fds.as_mut_ptr().cast(), flags.bits()) };

    Errno::result(res)?;

    // SAFETY: pipe2 returns a valid array of fds.
    let [read, write] = unsafe { fds.assume_init() };
    Ok((read, write))
}

#[expect(clippy::cast_possible_truncation)]
pub(crate) const PF_UNSPEC: libc::sa_family_t = libc::AF_UNSPEC as libc::sa_family_t;
#[expect(clippy::cast_possible_truncation)]
pub(crate) const PF_UNIX: libc::sa_family_t = libc::AF_UNIX as libc::sa_family_t;
#[expect(clippy::cast_possible_truncation)]
pub(crate) const PF_INET: libc::sa_family_t = libc::AF_INET as libc::sa_family_t;
#[expect(clippy::cast_possible_truncation)]
pub(crate) const PF_INET6: libc::sa_family_t = libc::AF_INET6 as libc::sa_family_t;
#[expect(clippy::cast_possible_truncation)]
pub(crate) const PF_ALG: libc::sa_family_t = libc::AF_ALG as libc::sa_family_t;
#[expect(clippy::cast_possible_truncation)]
pub(crate) const PF_NETLINK: libc::sa_family_t = libc::AF_NETLINK as libc::sa_family_t;
/* From <bits/socket.h>, expect this to be updated regularly. */
pub(crate) const PF_MAX: libc::sa_family_t = 46;

/// nix' SockAddrLike.family() function does not support AF_ALG.
/// This is a workaround that accesses the underlying sockaddr directly.
pub(crate) fn addr_family<T: SockaddrLike>(addr: &T) -> libc::sa_family_t {
    // SAFETY: This is safe as long as addr.as_ptr() returns a valid pointer to a sockaddr.
    unsafe { (*addr.as_ptr()).sa_family }
}

/// Want/got stx_mode & S_IFMT.
pub const STATX_TYPE: libc::c_uint = 0x00000001;
/// Want/got stx_mode & ~S_IFMT.
pub const STATX_MODE: libc::c_uint = 0x00000002;
/// Want/got stx_nlink.
pub const STATX_NLINK: libc::c_uint = 0x00000004;
/// Want/got stx_uid.
pub const STATX_UID: libc::c_uint = 0x00000008;
/// Want/got stx_gid.
pub const STATX_GID: libc::c_uint = 0x00000010;
/// Want/got stx_atime.
pub const STATX_ATIME: libc::c_uint = 0x00000020;
/// Want/got stx_mtime.
pub const STATX_MTIME: libc::c_uint = 0x00000040;
/// Want/got stx_ctime.
pub const STATX_CTIME: libc::c_uint = 0x00000080;
/// Want/got stx_ino.
pub const STATX_INO: libc::c_uint = 0x00000100;
/// Want/got stx_size.
pub const STATX_SIZE: libc::c_uint = 0x00000200;
/// Want/got stx_blocks.
pub const STATX_BLOCKS: libc::c_uint = 0x00000400;
/// Want all the basic stat information.
pub const STATX_BASIC_STATS: libc::c_uint = 0x000007ff;
/// Want/got stx_btime.
pub const STATX_BTIME: libc::c_uint = 0x00000800;
/// Want/Got stx_mnt_id.
pub const STATX_MNT_ID: libc::c_uint = 0x00001000;
/// Want/got direct I/O alignment info.
pub const STATX_DIOALIGN: libc::c_uint = 0x00002000;
/// Want/got extended stx_mount_id, requires Linux>=6.8.
pub const STATX_MNT_ID_UNIQUE: libc::c_uint = 0x00004000;
/// Want/got stx_subvol.
pub const STATX_SUBVOL: libc::c_uint = 0x00008000;
/// Want/got atomic_write_* fields.
pub const STATX_WRITE_ATOMIC: libc::c_uint = 0x00010000;
/// Want/got dio read alignment info.
pub const STATX_DIO_READ_ALIGN: libc::c_uint = 0x00020000;

/// Do what stat(2) does, default.
pub const AT_STATX_SYNC_AS_STAT: libc::c_int = 0x0000;

/// Sync changes with the remote filesystem.
pub const AT_STATX_FORCE_SYNC: libc::c_int = 0x2000;

/// Do not sync with remote filesystem.
pub const AT_STATX_DONT_SYNC: libc::c_int = 0x4000;

/// Safe statx() wrapper.
pub fn statx<Fd: AsFd, P: ?Sized + NixPath>(
    dirfd: Fd,
    pathname: &P,
    flags: libc::c_int,
    mask: libc::c_uint,
) -> Result<FileStatx, Errno> {
    let dirfd = dirfd.as_fd().as_raw_fd();
    let mut dst = std::mem::MaybeUninit::uninit();

    // SAFETY: Neither nix nor libc has a wrapper for statx.
    Errno::result(pathname.with_nix_path(|cstr| unsafe {
        libc::syscall(
            libc::SYS_statx,
            dirfd,
            cstr.as_ptr(),
            flags,
            mask,
            dst.as_mut_ptr(),
        )
    })?)?;

    // SAFETY: statx returned success.
    Ok(unsafe { dst.assume_init() })
}

/// Safe statx() wrapper to use with a FD only.
pub fn fstatx<Fd: AsFd>(fd: Fd, mask: libc::c_uint) -> Result<FileStatx, Errno> {
    let fd = fd.as_fd().as_raw_fd();
    let mut dst = std::mem::MaybeUninit::uninit();

    // SAFETY: Neither nix nor libc has a wrapper for statx.
    Errno::result(unsafe {
        libc::syscall(
            libc::SYS_statx,
            fd,
            c"".as_ptr(),
            libc::AT_EMPTY_PATH,
            mask,
            dst.as_mut_ptr(),
        )
    })?;

    // SAFETY: statx returned success.
    Ok(unsafe { dst.assume_init() })
}

/// Wrapper for struct stat64.
pub(crate) use libc::stat64 as FileStat64;

pub(crate) fn fstatat64<P: ?Sized + NixPath>(
    dirfd: Option<RawFd>,
    pathname: &P,
    flags: libc::c_int,
) -> Result<FileStat64, Errno> {
    let dirfd = dirfd.unwrap_or(libc::AT_FDCWD);
    let mut dst = std::mem::MaybeUninit::uninit();

    // SAFETY: nix does not has a wrapper for fstatat64.
    Errno::result(pathname.with_nix_path(|cstr| unsafe {
        libc::fstatat64(dirfd, cstr.as_ptr(), dst.as_mut_ptr(), flags)
    })?)?;

    // SAFETY: fstatat64 returned success.
    Ok(unsafe { dst.assume_init() })
}

#[cfg(target_os = "freebsd")]
type fs_type_t = u32;
#[cfg(target_os = "android")]
type fs_type_t = libc::c_ulong;
#[cfg(all(target_os = "linux", target_arch = "s390x", not(target_env = "musl")))]
type fs_type_t = libc::c_uint;
#[cfg(all(target_os = "linux", target_env = "musl"))]
type fs_type_t = libc::c_ulong;
#[cfg(all(target_os = "linux", target_env = "ohos"))]
type fs_type_t = libc::c_ulong;
#[cfg(all(target_os = "linux", target_env = "uclibc"))]
type fs_type_t = libc::c_int;
#[cfg(all(
    target_os = "linux",
    not(any(
        target_arch = "s390x",
        target_env = "musl",
        target_env = "ohos",
        target_env = "uclibc"
    ))
))]
type fs_type_t = libc::__fsword_t;

const BTRFS_SUPER_MAGIC: fs_type_t = libc::BTRFS_SUPER_MAGIC as fs_type_t;
const HUGETLBFS_MAGIC: fs_type_t = libc::HUGETLBFS_MAGIC as fs_type_t;
const OVERLAYFS_SUPER_MAGIC: fs_type_t = libc::OVERLAYFS_SUPER_MAGIC as fs_type_t;
const PROC_SUPER_MAGIC: fs_type_t = libc::PROC_SUPER_MAGIC as fs_type_t;

/// Wrapper for struct statfs64
pub(crate) struct Statfs64(libc::statfs64);

impl Statfs64 {
    // WORKAROUND:
    // Check if the file resides on a btrfs|overlayfs.
    // Overlayfs does not report device IDs correctly on
    // fstat, which is a known bug:
    // https://github.com/moby/moby/issues/43512
    // Btrfs has the same issue:
    // https://www.reddit.com/r/btrfs/comments/1clgd8u/different_dev_id_reported_by_statx_and/
    // Assume true on errors for safety.
    pub(crate) fn has_broken_device_ids(&self) -> bool {
        matches!(self.0.f_type, OVERLAYFS_SUPER_MAGIC | BTRFS_SUPER_MAGIC)
    }

    // Check if file resides on a hugetlbfs.
    pub(crate) fn is_huge_file(&self) -> bool {
        self.0.f_type == HUGETLBFS_MAGIC
    }

    // Check if file resides on a procfs.
    pub(crate) fn is_proc(&self) -> bool {
        self.0.f_type == PROC_SUPER_MAGIC
    }
}

/// Safe wrapper for fstatfs64
pub(crate) fn fstatfs64<Fd: AsFd>(fd: Fd) -> Result<Statfs64, Errno> {
    let mut dst = std::mem::MaybeUninit::uninit();

    // SAFETY: nix does not have a wrapper for fstatfs64.
    Errno::result(unsafe { libc::fstatfs64(fd.as_fd().as_raw_fd(), dst.as_mut_ptr()) })?;

    // SAFETY: fstatfs64 returned success.
    Ok(Statfs64(unsafe { dst.assume_init() }))
}

/// Safe wrapper for epoll_ctl with detailed error handling.
pub fn epoll_ctl_safe<E: AsFd>(
    epoll: &E,
    fd: RawFd,
    event: Option<libc::epoll_event>,
) -> Result<(), Errno> {
    let (result, ignore_errno) = if let Some(mut event) = event {
        (
            // SAFETY: nix deprecated epoll_ctl and Epoll requires an OwnedFd...
            // Ignore EEXIST for EPOLL_CTL_ADD.
            Errno::result(unsafe {
                libc::epoll_ctl(
                    epoll.as_fd().as_raw_fd(),
                    EpollOp::EpollCtlAdd as libc::c_int,
                    fd,
                    &raw mut event,
                )
            }),
            Errno::EEXIST,
        )
    } else {
        (
            // SAFETY: nix deprecated epoll_ctl and Epoll requires an OwnedFd...
            // Ignore ENOENT for EPOLL_CTL_DEL.
            Errno::result(unsafe {
                libc::epoll_ctl(
                    epoll.as_fd().as_raw_fd(),
                    EpollOp::EpollCtlDel as libc::c_int,
                    fd,
                    std::ptr::null_mut(),
                )
            }),
            Errno::ENOENT,
        )
    };
    match result {
        Ok(_) => Ok(()),
        Err(errno) if errno == ignore_errno => Ok(()),
        Err(errno) => Err(errno),
    }
}

/// Safe wrapper for epoll_ctl_mod with detailed error handling.
pub fn epoll_ctl_mod_safe<E: AsFd>(
    epoll: &E,
    fd: RawFd,
    mut event: libc::epoll_event,
) -> Result<(), Errno> {
    // SAFETY: In libc we trust.
    Errno::result(unsafe {
        libc::epoll_ctl(
            epoll.as_fd().as_raw_fd(),
            EpollOp::EpollCtlMod as libc::c_int,
            fd,
            &raw mut event,
        )
    })
    .map(drop)
}

const EPIOCSPARAMS: u64 = 0x40088a01;
const EPIOCGPARAMS: u64 = 0x80088a02;

/// Epoll parameters
#[repr(C)]
pub struct EpollParams {
    /// Number of usecs to busy poll
    pub busy_poll_usecs: u32,
    /// Max packets per poll
    pub busy_poll_budget: u16,
    /// Boolean preference
    pub prefer_busy_poll: u16,
    // pad the struct to a multiple of 64bits
    // must be zero.
    pad: u8,
}

impl EpollParams {
    /// Create a new EpollParams structure.
    pub fn new(busy_poll_usecs: u32, busy_poll_budget: u16, prefer_busy_poll: bool) -> Self {
        let prefer_busy_poll = if prefer_busy_poll { 1 } else { 0 };
        Self {
            busy_poll_usecs,
            busy_poll_budget,
            prefer_busy_poll,
            pad: 0,
        }
    }
}

impl Serialize for EpollParams {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(3))?; // We expect 3 fields.

        // Serialize busy_poll_usecs field.
        map.serialize_entry("busy_poll_usecs", &self.busy_poll_usecs)?;

        // Serialize busy_poll_budget field.
        map.serialize_entry("busy_poll_budget", &self.busy_poll_budget)?;

        // Serialize prefer_busy_poll.
        map.serialize_entry("prefer_busy_poll", &(self.prefer_busy_poll != 0))?;

        map.end()
    }
}

/// Set epoll parameters for the given epoll file descriptor.
/// Requires Linux>=6.9.
pub fn epoll_set_params<Fd: AsFd>(fd: Fd, params: &EpollParams) -> Result<(), Errno> {
    // SAFETY: In libc we trust.
    Errno::result(unsafe {
        libc::syscall(
            libc::SYS_ioctl,
            fd.as_fd().as_raw_fd(),
            EPIOCSPARAMS,
            params,
        )
    })
    .map(drop)
}

/// Get epoll parameters for the given epoll file descriptor.
/// Requires Linux>=6.9.
pub fn epoll_get_params<Fd: AsFd>(fd: Fd) -> Result<EpollParams, Errno> {
    let mut params = std::mem::MaybeUninit::uninit();

    // SAFETY: In libc we trust.
    Errno::result(unsafe {
        libc::syscall(
            libc::SYS_ioctl,
            fd.as_fd().as_raw_fd(),
            EPIOCGPARAMS,
            params.as_mut_ptr(),
        )
    })?;

    // SAFETY: ioctl returned success.
    Ok(unsafe { params.assume_init() })
}

/// Uses getsockopt SO_DOMAIN to get the domain of the given socket.
pub fn getsockdomain<Fd: AsFd>(fd: Fd) -> Result<libc::c_int, Errno> {
    #[expect(clippy::cast_possible_truncation)]
    let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
    let mut fml: libc::c_int = 0;

    // SAFETY: In libc we trust.
    Errno::result(unsafe {
        libc::getsockopt(
            fd.as_fd().as_raw_fd(),
            libc::SOL_SOCKET,
            libc::SO_DOMAIN,
            std::ptr::addr_of_mut!(fml) as *mut _,
            &raw mut len,
        )
    })?;

    Ok(fml)
}

/// Unique identifiers for Linux Security Modules.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LsmId {
    Undef,
    Capability,
    Selinux,
    Smack,
    Tomoyo,
    AppArmor,
    Yama,
    LoadPin,
    SafeSetID,
    Lockdown,
    Bpf,
    Landlock,
    Ima,
    Evm,
    Ipe,
    Unknown(u64),
}

impl From<u64> for LsmId {
    fn from(id: u64) -> Self {
        match id {
            0 => LsmId::Undef,
            100 => LsmId::Capability,
            101 => LsmId::Selinux,
            102 => LsmId::Smack,
            103 => LsmId::Tomoyo,
            104 => LsmId::AppArmor,
            105 => LsmId::Yama,
            106 => LsmId::LoadPin,
            107 => LsmId::SafeSetID,
            108 => LsmId::Lockdown,
            109 => LsmId::Bpf,
            110 => LsmId::Landlock,
            111 => LsmId::Ima,
            112 => LsmId::Evm,
            113 => LsmId::Ipe,
            other => LsmId::Unknown(other),
        }
    }
}

impl std::fmt::Display for LsmId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LsmId::Undef => write!(f, "undef"),
            LsmId::Capability => write!(f, "capability"),
            LsmId::Selinux => write!(f, "selinux"),
            LsmId::Smack => write!(f, "smack"),
            LsmId::Tomoyo => write!(f, "tomoyo"),
            LsmId::AppArmor => write!(f, "apparmor"),
            LsmId::Yama => write!(f, "yama"),
            LsmId::LoadPin => write!(f, "loadpin"),
            LsmId::SafeSetID => write!(f, "safesetid"),
            LsmId::Lockdown => write!(f, "lockdown"),
            LsmId::Bpf => write!(f, "bpf"),
            LsmId::Landlock => write!(f, "landlock"),
            LsmId::Ima => write!(f, "ima"),
            LsmId::Evm => write!(f, "evm"),
            LsmId::Ipe => write!(f, "ipe"),
            LsmId::Unknown(id) => write!(f, "unknown({id})"),
        }
    }
}

/// LazyLock-initialized system call number for `lsm_list_modules`.
pub static SYS_LSM_LIST_MODULES: LazyLock<libc::c_long> = LazyLock::new(|| {
    ScmpSyscall::from_name("lsm_list_modules")
        .map(i32::from)
        .map(libc::c_long::from)
        .unwrap_or(0)
});

/// Safe wrapper around the `lsm_list_modules` syscall. Requires Linux >= 6.10.
pub fn lsm_list_modules() -> Result<Vec<LsmId>, Errno> {
    let sysno = *SYS_LSM_LIST_MODULES;
    if sysno == 0 {
        return Err(Errno::ENOSYS);
    }

    let mut size: u32 = 0;
    let res = Errno::result(
        // SAFETY: Zero-length buffer & valid pointer to `size`.
        unsafe {
            libc::syscall(
                sysno as libc::c_long,
                std::ptr::null_mut::<u64>(),
                std::ptr::addr_of_mut!(size),
                0u32,
            )
        },
    );

    match res {
        Ok(0) => return Err(Errno::ENOENT),
        Ok(_) => return Err(Errno::EINVAL),
        Err(Errno::E2BIG) => {} // size is filled!
        Err(errno) => return Err(errno),
    }

    if size == 0 {
        // No modules loaded.
        return Err(Errno::ENOENT);
    }

    let count = (size / 8) as usize;
    let mut buf = vec![0u64; count];
    #[expect(clippy::cast_possible_truncation)]
    #[expect(clippy::cast_sign_loss)]
    let count = Errno::result(
        // SAFETY: Properly allocated buffer & valid pointer to `size`.
        unsafe {
            libc::syscall(
                sysno as libc::c_long,
                buf.as_mut_ptr(),
                std::ptr::addr_of_mut!(size),
                0u32,
            )
        },
    )
    .map(|res| res as usize)?;

    if count == 0 {
        // No modules loaded.
        return Err(Errno::ENOENT);
    }

    // Populate output array.
    let mut out = Vec::with_capacity(count);
    for item in buf.iter().take(count).copied().map(LsmId::from) {
        out.push(item)
    }
    Ok(out)
}

// nix does not define RenameFlags for musl.
bitflags! {
    /// Flags for use with `renameat2`.
    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    #[repr(transparent)]
    pub struct RenameFlags: u32 {
        /// Don't overwrite `new_path` of the rename;
        /// return an error if `new_path` already exists.
        const RENAME_NOREPLACE = 1;

        /// Atomically exchange `old_path` and `new_path`.
        /// Both paths must exist.
        const RENAME_EXCHANGE  = 2;

        /// Create a "whiteout" at the source of the rename
        /// (for overlay/union filesystems).
        const RENAME_WHITEOUT  = 4;
    }
}

bitflags! {
    /// Flags used with `send`, `recv`, etc.
    // Keep in sync with <linux/socket.h>!
    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    #[repr(transparent)]
    pub struct MsgFlags: i32 {
        /// Process out-of-band data.
        const MSG_OOB = 0x01;
        /// Peek at incoming messages.
        const MSG_PEEK = 0x02;
        /// Don't use local routing.
        const MSG_DONTROUTE = 0x04;
        /// DECnet uses a different name for MSG_DONTROUTE.
        const MSG_TRYHARD = Self::MSG_DONTROUTE.bits();
        /// Control data lost before delivery.
        const MSG_CTRUNC = 0x08;
        /// Supply or ask second address.
        const MSG_PROXY = 0x10;
        /// Truncated message.
        const MSG_TRUNC = 0x20;
        /// Nonblocking IO.
        const MSG_DONTWAIT = 0x40;
        /// End of record.
        const MSG_EOR = 0x80;
        /// Wait for a full request.
        const MSG_WAITALL = 0x100;
        /// End of connection.
        const MSG_FIN = 0x200;
        /// Synchronous operation.
        const MSG_SYN = 0x400;
        /// Confirm path validity.
        const MSG_CONFIRM = 0x800;
        /// Reset connection.
        const MSG_RST = 0x1000;
        /// Fetch message from error queue.
        const MSG_ERRQUEUE = 0x2000;
        /// Do not generate SIGPIPE.
        const MSG_NOSIGNAL = 0x4000;
        /// Sender will send more data.
        const MSG_MORE = 0x8000;
        /// Wait for at least one packet to return.
        const MSG_WAITFORONE = 0x10000;
        /// More messages coming.
        const MSG_BATCH = 0x40000;
        /// Receive devmem skbs as cmsg.
        const MSG_SOCK_DEVMEM = 0x2000000;
        /// Use user data in kernel path.
        const MSG_ZEROCOPY = 0x4000000;
        /// Send data in TCP SYN.
        const MSG_FASTOPEN = 0x20000000;
        /// Set close_on_exit for file descriptors.
        const MSG_CMSG_CLOEXEC = 0x40000000;
        /// Special flag for notifications.
        const MSG_NOTIFICATION = Self::MSG_MORE.bits();
    }
}

#[expect(clippy::disallowed_types)]
use nix::sys::socket::MsgFlags as NixMsgFlags;

#[expect(clippy::disallowed_types)]
impl From<MsgFlags> for NixMsgFlags {
    fn from(msgflags: MsgFlags) -> Self {
        Self::from_bits_retain(msgflags.bits())
    }
}

#[expect(clippy::disallowed_types)]
impl From<NixMsgFlags> for MsgFlags {
    fn from(msgflags: NixMsgFlags) -> Self {
        Self::from_bits_retain(msgflags.bits())
    }
}

bitflags! {
    /// Flags used with inotify_add_watch(2).
    // Keep in sync with <linux/inotify.h>!
    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    #[repr(transparent)]
    pub struct AddWatchFlags: u32 {
        // The following are legal, implemented events that user-space can watch for.
        /// File was accessed.
        const IN_ACCESS = 0x00000001;
        /// File was modified.
        const IN_MODIFY = 0x00000002;
        /// Metadata changed.
        const IN_ATTRIB = 0x00000004;
        /// Writable file was closed.
        const IN_CLOSE_WRITE = 0x00000008;
        /// Unwritable file closed.
        const IN_CLOSE_NOWRITE = 0x00000010;
        /// File was opened.
        const IN_OPEN = 0x00000020;
        /// File was moved from X.
        const IN_MOVED_FROM = 0x00000040;
        /// File was moved to Y.
        const IN_MOVED_TO = 0x00000080;
        /// Subfile was created.
        const IN_CREATE = 0x00000100;
        /// Subfile was deleted.
        const IN_DELETE = 0x00000200;
        /// Self was deleted.
        const IN_DELETE_SELF = 0x00000400;
        /// Self was moved.
        const IN_MOVE_SELF = 0x00000800;

        // The following are legal events. They are sent as needed to any watch.
        /// Backing fs was unmounted.
        const IN_UNMOUNT = 0x00002000;
        /// Event queued overflowed.
        const IN_Q_OVERFLOW = 0x00004000;
        /// File was ignored.
        const IN_IGNORED = 0x00008000;

        // Helper events.
        /// Helper event: Close.
        const IN_CLOSE = Self::IN_CLOSE_WRITE.bits() | Self::IN_CLOSE_NOWRITE.bits();
        /// Helper event: Moves.
        const IN_MOVE = Self::IN_MOVED_FROM.bits() | Self::IN_MOVED_TO.bits();

        // Special flags.
        /// Only watch the path if it is a directory.
        const IN_ONLYDIR = 0x01000000;
        /// Don't follow a sym link.
        const IN_DONT_FOLLOW = 0x02000000;
        /// Exclude events on unlinked objects.
        const IN_EXCL_UNLINK = 0x04000000;
        /// Only create watches.
        const IN_MASK_CREATE = 0x10000000;
        /// Add to the mask of an already existing watch.
        const IN_MASK_ADD = 0x20000000;
        /// Event occurred against dir.
        const IN_ISDIR = 0x40000000;
        /// Only send event once.
        const IN_ONESHOT = 0x80000000;

        /*
         * All of the events - we build the list by hand so that we can add flags in
         * the future and not break backward compatibility. Apps will get only the
         * events that they originally wanted. Be sure to add new events here!
         */
        const IN_ALL_EVENTS =
            Self::IN_ACCESS.bits() |
            Self::IN_MODIFY.bits() |
            Self::IN_ATTRIB.bits() |
            Self::IN_CLOSE_WRITE.bits() |
            Self::IN_CLOSE_NOWRITE.bits() |
            Self::IN_OPEN.bits() |
            Self::IN_MOVED_FROM.bits() |
            Self::IN_MOVED_TO.bits() |
            Self::IN_DELETE.bits() |
            Self::IN_CREATE.bits() |
            Self::IN_DELETE_SELF.bits() |
            Self::IN_MOVE_SELF.bits();
    }
}

#[expect(clippy::disallowed_types)]
use nix::sys::inotify::AddWatchFlags as NixAddWatchFlags;

#[expect(clippy::disallowed_types)]
impl From<AddWatchFlags> for NixAddWatchFlags {
    fn from(addwatchflags: AddWatchFlags) -> Self {
        Self::from_bits_retain(addwatchflags.bits())
    }
}

#[expect(clippy::disallowed_types)]
impl From<NixAddWatchFlags> for AddWatchFlags {
    fn from(addwatchflags: NixAddWatchFlags) -> Self {
        Self::from_bits_retain(addwatchflags.bits())
    }
}

bitflags! {
    /// Flags for memfd_create(2)
    // nix' MFdFlags does not include MFD_{EXEC,NOEXEC_SEAL} yet!
    #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    #[repr(transparent)]
    pub struct MFdFlags: libc::c_uint {
        /// Close-on-exec
        const MFD_CLOEXEC = libc::MFD_CLOEXEC;

        /// Allow sealing via _fcntl_(2).
        const MFD_ALLOW_SEALING = libc::MFD_ALLOW_SEALING;

        /// Disallow exec (Linux >= 6.3).
        const MFD_NOEXEC_SEAL = libc::MFD_NOEXEC_SEAL;

        /// Allow exec (Linux >= 6.3).
        const MFD_EXEC = libc::MFD_EXEC;

        /// Use hugetlbfs.
        const MFD_HUGETLB = libc::MFD_HUGETLB;

        /// Huge page size: 1MB.
        const MFD_HUGE_1MB = libc::MFD_HUGE_1MB;

        /// Huge page size: 2MB.
        const MFD_HUGE_2MB = libc::MFD_HUGE_2MB;

        /// Huge page size: 8MB.
        const MFD_HUGE_8MB = libc::MFD_HUGE_8MB;

        /// Huge page size: 16MB.
        const MFD_HUGE_16MB = libc::MFD_HUGE_16MB;

        /// Huge page size: 32MB.
        const MFD_HUGE_32MB = libc::MFD_HUGE_32MB;

        /// Huge page size: 256MB.
        const MFD_HUGE_256MB = libc::MFD_HUGE_256MB;

        /// Huge page size: 512MB.
        const MFD_HUGE_512MB = libc::MFD_HUGE_512MB;

        /// Huge page size: 1GB.
        const MFD_HUGE_1GB = libc::MFD_HUGE_1GB;

        /// Huge page size: 2GB.
        const MFD_HUGE_2GB = libc::MFD_HUGE_2GB;

        /// Huge page size: 16GB.
        const MFD_HUGE_16GB = libc::MFD_HUGE_16GB;
    }
}

#[expect(clippy::disallowed_types)]
use nix::sys::memfd::MFdFlags as NixMFdFlags;

#[expect(clippy::disallowed_types)]
impl From<MFdFlags> for NixMFdFlags {
    fn from(mfdflags: MFdFlags) -> Self {
        Self::from_bits_retain(mfdflags.bits())
    }
}

#[expect(clippy::disallowed_types)]
impl From<NixMFdFlags> for MFdFlags {
    fn from(mfdflags: NixMFdFlags) -> Self {
        Self::from_bits_retain(mfdflags.bits())
    }
}

/*
 * Constants from <linux/limits.h> not defined by libc yet.
 */

// # chars in an extended attribute name.
pub(crate) const XATTR_NAME_MAX: usize = 255;
// size of an extended attribute value (64k).
pub(crate) const XATTR_SIZE_MAX: usize = 1 << 16;
// size of extended attribute namelist (64k).
pub(crate) const XATTR_LIST_MAX: usize = 1 << 16;