syd 3.58.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
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
//
// Syd: rock-solid application kernel
// src/proc/util.rs: proc(5) utilities
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
// proc_auxv function is based in part upon procfs crate which is:
//   Copyright (c) 2015 The procfs Developers
//   SPDX-License-Identifier: MIT
// /proc/pid/stat* parsing functions are based in part upon procinfo-rs crate which is:
//   Copyright (c) 2015 The Rust Project Developers
//   SPDX-License-Identifier: MIT
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY: This module has (almost) been liberated from unsafe code!
// proc_set_at_secure_* tests call fork(2) therefore they need unsafe.
// Use deny rather than forbid so we can allow these cases.
#![deny(unsafe_code)]

use std::{
    ffi::{OsStr, OsString},
    fmt,
    io::{BufReader, Cursor, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write},
    ops::Range,
    os::{
        fd::{AsFd, AsRawFd, RawFd},
        unix::ffi::{OsStrExt, OsStringExt},
    },
};

use bitflags::bitflags;
use btoi::{btoi, btoi_radix};
use memchr::{arch::all::is_prefix, memrchr};
use nix::{
    errno::Errno,
    fcntl::OFlag,
    libc::pid_t,
    sys::{
        stat::Mode,
        uio::{process_vm_readv, process_vm_writev, RemoteIoVec},
    },
    unistd::{getpid, gettid, lseek64, Gid, Pid, Uid, Whence},
    NixPath,
};
use procfs_core::{
    net::UnixNetEntries,
    process::{LimitValue, MMapPath, Namespace, Namespaces},
    FromBufRead,
};
use serde::{ser::SerializeMap, Serialize, Serializer};

use super::{
    info::{CharDevice, PROC_INFO},
    maps::proc_maps,
};
use crate::{
    compat::{
        getdents64, openat2, pidfd_get_tgid, readlinkat, statx, OpenHow, ResolveFlag, STATX_INO,
    },
    config::*,
    cookie::{safe_sysinfo, safe_write},
    elf::ElfType,
    err::{btoi2err, err2no, proc_errno, proc_error_to_errno},
    fd::{is_empty_file, is_open_fd, is_proc, parse_fd, SafeOwnedFd, AT_BADFD, PROC_FILE},
    hash::{SydHashMap, SydHashSet},
    io::{read_all, read_buf, write_all},
    lookup::safe_open,
    parsers::{
        map_result,
        proc::{
            parse_max_open_files, parse_pidfd_info_pid, parse_proc_char_dev, parse_stat,
            parse_statm, parse_status, parse_status_interrupt, parse_status_tgid,
            parse_status_umask, parse_tty,
        },
        read_to_end,
    },
    path::{XPathBuf, XPathCow},
    retry::retry_on_eintr,
    rng::randint,
    sandbox::Sandbox,
    sigset::SydSigSet,
    xfmt, XPath,
};

/// Process memory usage information.
///
/// All values are in units of pages.
///
/// See `man 5 proc` and `Linux/fs/proc/array.c`.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Statm {
    /// Total virtual memory size.
    pub size: u64,
}

/// Process status information.
///
/// See `man 5 proc` and `Linux/fs/proc/array.c`.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Stat {
    /// Number of threads in this process (since Linux 2.6).
    pub num_threads: u64,
    /// The address above which program heap can be expanded with brk(2).
    pub startbrk: u64,
    /// The address of the start (i.e., bottom) of the stack.
    pub startstack: u64,
    /// The controlling terminal of the process. (The minor device
    /// number is contained in the combination of bits 31 to 20 and 7 to
    /// 0; the major device number is in bits 15 to 8.)
    pub tty_nr: i32,
}

/// Process status information.
///
/// See `man 5 proc` and `Linux/fs/proc/array.c`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Status {
    /// File mode creation mask (since Linux 4.7).
    pub umask: Mode,
    /// Process ID (i.e., Thread Group ID).
    pub pid: Pid,
    /// Number of signals pending for the thread (see pthreads(7)).
    pub sig_pending_thread: SydSigSet,
    /// Number of signals pending for the process (see signal(7)).
    pub sig_pending_process: SydSigSet,
    /// Mask indicating signals being blocked.
    pub sig_blocked: SydSigSet,
    /// Mask indicating signals being ignored.
    pub sig_ignored: SydSigSet,
    /// Mask indicating signals being caught.
    pub sig_caught: SydSigSet,
}

// Default is used by parsers.
// Pid has no default therefore this is needed.
impl Default for Status {
    fn default() -> Self {
        Self {
            umask: Mode::empty(),
            pid: Pid::from_raw(0),
            sig_pending_thread: SydSigSet::default(),
            sig_pending_process: SydSigSet::default(),
            sig_blocked: SydSigSet::default(),
            sig_ignored: SydSigSet::default(),
            sig_caught: SydSigSet::default(),
        }
    }
}

impl Serialize for Status {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(7))?;
        map.serialize_entry("umask", &self.umask.bits())?;
        map.serialize_entry("pid", &self.pid.as_raw())?;
        map.serialize_entry("sig_pending_thread", &self.sig_pending_thread)?;
        map.serialize_entry("sig_pending_process", &self.sig_pending_process)?;
        map.serialize_entry("sig_blocked", &self.sig_blocked)?;
        map.serialize_entry("sig_ignored", &self.sig_ignored)?;
        map.serialize_entry("sig_caught", &self.sig_caught)?;
        map.end()
    }
}

/// Safe `OFlags` to use when opening proc(5) files.
pub const OFLAG_PROC: OFlag =
    OFlag::from_bits_retain(libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NOCTTY);

/// Safe `ResolveFlag` to use when opening proc(5) files.
pub const RFLAG_PROC: ResolveFlag = ResolveFlag::from_bits_retain(
    ResolveFlag::RESOLVE_NO_MAGICLINKS.bits()
        | ResolveFlag::RESOLVE_NO_SYMLINKS.bits()
        | ResolveFlag::RESOLVE_BENEATH.bits()
        | ResolveFlag::RESOLVE_NO_XDEV.bits(),
);

/// Function to safely open a proc(5) file and return an `SafeOwnedFd`.
pub fn safe_open_proc<P: NixPath + ?Sized>(path: &P) -> Result<SafeOwnedFd, Errno> {
    safe_open(PROC_FILE(), path, OFLAG_PROC, RFLAG_PROC)
}

fn read_usize_from_ne_bytes(bytes: &[u8], ptr_size: usize) -> Result<usize, Errno> {
    match ptr_size {
        4 => {
            if bytes.len() < 4 {
                return Err(Errno::EFAULT);
            }
            Ok(usize::try_from(u32::from_ne_bytes(
                bytes[..4].try_into().or(Err(Errno::EINVAL))?,
            ))
            .or(Err(Errno::EINVAL))?)
        }
        8 => {
            if bytes.len() < 8 {
                return Err(Errno::EFAULT);
            }
            Ok(usize::try_from(u64::from_ne_bytes(
                bytes[..8].try_into().or(Err(Errno::EINVAL))?,
            ))
            .or(Err(Errno::EINVAL))?)
        }
        _ => Err(Errno::EINVAL),
    }
}

fn usize_to_ne_bytes(value: usize, sizeof_ptr: usize) -> Vec<u8> {
    #[expect(clippy::cast_possible_truncation)]
    match sizeof_ptr {
        4 => (value as u32).to_ne_bytes().to_vec(),
        8 => (value as u64).to_ne_bytes().to_vec(),
        _ => unreachable!("Invalid pointer size!"),
    }
}

/// Return the stat of the given process.
pub fn proc_stat(pid: Pid) -> Result<Stat, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"stat")?;

    // Safely open proc(5) file.
    let file = safe_open_proc(&path).map_err(proc_errno)?;

    let mut buf = [0; 1024]; // A typical stat file is about 300 bytes.
    map_result(parse_stat(read_to_end(file, &mut buf)?))
}

/// Return the memory stat of the given process.
pub fn proc_statm(pid: Pid) -> Result<Statm, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"statm")?;

    // Safely open proc(5) file.
    let file = safe_open_proc(&path).map_err(proc_errno)?;

    let mut buf = [0; 256]; // A typical statm file is about 25 bytes.
    map_result(parse_statm(read_to_end(file, &mut buf)?))
}

/// Return the status of the given process.
pub fn proc_status(pid: Pid) -> Result<Status, Errno> {
    proc_status_read(proc_status_open(pid)?)
}

/// Calculate interrupt sigset from proc_pid_status(5).
///
/// Returns pending, unblocked, caught signals.
pub fn proc_interrupt(pid: Pid) -> Result<SydSigSet, Errno> {
    proc_interrupt_read(proc_status_open(pid)?)
}

/// Open a FD to /proc/$pid/status and return a SafeOwnedFd.
pub fn proc_status_open(pid: Pid) -> Result<SafeOwnedFd, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"status")?;

    safe_open_proc(&path).map_err(proc_errno)
}

/// Return the status of the given process from the given Fd.
pub fn proc_status_read<Fd: AsFd>(fd: Fd) -> Result<Status, Errno> {
    // A typical status file is about 1500 bytes.
    //
    // SAFETY: read_to_end will return EOVERFLOW if
    // proc_pid_status(5) ever grows beyond 2048 bytes
    // so we will know.
    let mut buf = [0; 2048];

    map_result(parse_status(read_to_end(fd, &mut buf)?))
}

/// Calculate interrupt sigset from proc_pid_status(5).
///
/// Returns pending, unblocked, caught signals.
pub fn proc_interrupt_read<Fd: AsFd>(fd: Fd) -> Result<SydSigSet, Errno> {
    // Read up to 1408 bytes.
    let mut buf = [0u8; 1408];
    let nread = read_buf(fd, &mut buf)?;

    map_result(parse_status_interrupt(&buf[..nread]))
}

/// Retrieves the thread group ID (TGID) for the specified thread ID (TID).
pub fn proc_tgid(tid: Pid) -> Result<Pid, Errno> {
    // This function is a hot-path, so we provide a specialized impl.
    // proc_status(tid).map(|stat| stat.pid)
    let fd = proc_status_open(tid)?;

    // Read up to 192 bytes.
    let mut data = [0u8; 192];
    let nread = read_buf(fd, &mut data)?;

    map_result(parse_status_tgid(&data[..nread]))
}

/// Get the umask of the given `Pid`.
pub fn proc_umask(pid: Pid) -> Result<Mode, Errno> {
    // This function is a hot-path, so we provide a specialized impl.
    // proc_status(pid).map(|stat| stat.umask)
    let fd = proc_status_open(pid)?;

    // Read up to 160 bytes.
    let mut data = [0u8; 160];
    let nread = read_buf(fd, &mut data)?;

    map_result(parse_status_umask(&data[..nread]))
}

/// Retrieve the TGID referred to by a pidfd.
///
/// Uses `PIDFD_GET_INFO` ioctl(2) on Linux-6.12 and newer,
/// falling back to `/proc/self/fdinfo` parsing on older kernels.
pub fn proc_pidfd_get_tgid<Fd: AsFd>(pidfd: Fd) -> Result<Pid, Errno> {
    if *HAVE_PIDFD_GET_INFO {
        return pidfd_get_tgid(&pidfd);
    }

    //
    // Fallback: Read /proc/thread-self/fdinfo/<pidfd>, and parse the Pid: field.
    //

    // Prepare path to proc_pid_fdinfo(5).
    let mut path = XPathBuf::from_pid(gettid())?;
    path.try_push(b"fdinfo")?;
    path.try_push_fd(pidfd.as_fd().as_raw_fd())?;

    // Open path without following symlinks.
    let file = safe_open(PROC_FILE(), &path, OFLAG_PROC, RFLAG_PROC).map_err(proc_errno)?;

    // A typical pidfd fdinfo is about 100-150 bytes.
    let mut buf = [0u8; 256];
    let nread = read_buf(file, &mut buf)?;

    map_result(parse_pidfd_info_pid(&buf[..nread]))
}

/// Locate stack and return the stack memory address range.
pub fn proc_stack(pid: Pid) -> Result<Range<u64>, Errno> {
    let maps = proc_maps(pid)?;

    // Iterate over each memory map entry.
    for map in maps {
        if let MMapPath::Stack = map.0.pathname {
            return Ok(map.0.address.0..map.0.address.1);
        }
    }

    Err(Errno::ENOENT)
}

/// Retrieves the address of the start of stack for the specified process ID (pid).
pub fn proc_stack_start(pid: Pid) -> Result<u64, Errno> {
    proc_stat(pid).map(|stat| stat.startstack)
}

/// Retrieves the current stack pointer (rsp) for the specified process ID (pid).
///
/// If the process is "running", it returns `Errno::EBUSY`.
pub fn proc_stack_pointer(pid: Pid) -> Result<u64, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"syscall")?;

    // Safely open proc(5) file.
    let file = safe_open_proc(&path).map_err(proc_errno)?;

    // SAFETY: read_to_end will return EOVERFLOW if
    // proc_pid_syscall(5) ever grows beyond 256 bytes
    // so we will know.
    let mut buf = [0u8; 256];
    let data = read_to_end(file, &mut buf)?;

    // Parse and return stack pointer.
    parse_stack_pointer(data)
}

// Parse the stack pointer from proc_pid_syscall(5) output.
fn parse_stack_pointer(data: &[u8]) -> Result<u64, Errno> {
    // Check if process is running.
    if is_prefix(data, b"running") {
        return Err(Errno::EBUSY);
    }

    // Find the last and previous space.
    let last_sp = match memrchr(b' ', data) {
        Some(i) => i,
        None => return Err(Errno::ENOENT),
    };

    let start = if let Some(prev) = memrchr(b' ', &data[..last_sp]) {
        prev.checked_add(1).ok_or(Errno::EOVERFLOW)?
    } else {
        0
    };

    // Convert the rsp value from hex to u64.
    let rsp = &data[start..last_sp];
    if let Some(hex) = rsp.strip_prefix(b"0x") {
        btoi_radix::<u64>(hex, 16).map_err(|err| btoi2err(&err))
    } else {
        Err(Errno::ENOENT)
    }
}

/// Get the auxiliary vector of the given `Pid`.
pub fn proc_auxv(pid: Pid, is32: bool) -> Result<SydHashMap<u64, u64>, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"auxv")?;

    // Safely open proc(5) file.
    let fd = safe_open_proc(&path).map_err(proc_errno)?;

    // Read all into the buffer.
    let buf = read_all(&fd)?;

    // Parse proc_pid_auxv(5).
    parse_auxv(&buf, is32)
}

// Parse a raw "/proc/<pid>/auxv" blob into a "{type -> value}" map.
fn parse_auxv(buf: &[u8], is32: bool) -> Result<SydHashMap<u64, u64>, Errno> {
    let mut map = SydHashMap::default();

    if buf.is_empty() {
        // Some kernel processes won't have any data for their auxv file.
        return Ok(map);
    }

    let mut fd = Cursor::new(buf);
    let mut word = [0u8; 8];
    let sizeof_ptr: usize = if is32 { 4 } else { 8 };
    loop {
        fd.read_exact(&mut word[..sizeof_ptr])
            .map_err(|err| err2no(&err))?;
        let key = read_usize_from_ne_bytes(&word[..sizeof_ptr], sizeof_ptr)? as u64;
        fd.read_exact(&mut word[..sizeof_ptr])
            .map_err(|err| err2no(&err))?;
        let value = read_usize_from_ne_bytes(&word[..sizeof_ptr], sizeof_ptr)? as u64;
        if key == 0 && value == 0 {
            break;
        }
        map.insert(key, value);
    }

    Ok(map)
}

/// Retrieves the current working directory (CWD) of the specified process ID (PID).
///
/// This function reads the symbolic link `/proc/<pid>/cwd` to determine the CWD.
pub fn proc_cwd(pid: Pid) -> Result<XPathBuf, Errno> {
    let path = XPathBuf::from_cwd(pid)?;
    readlinkat(PROC_FILE(), &path).map_err(proc_errno)
}

/// Retrieves the command name (comm) of the specified process ID (PID)
/// as a single string.
pub fn proc_comm(pid: Pid) -> Result<XPathBuf, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"comm")?;

    // Safely open proc(5) file.
    let file = safe_open_proc(&path).map_err(proc_errno)?;

    // Read up to 16 characters or until EOF.
    let mut comm = [0u8; 16];
    let mut nread = read_buf(file, &mut comm)?;

    // Remove the trailing NUL-byte and return an `XPathBuf`.
    let idx = nread.saturating_sub(1);
    if comm[idx] == 0 {
        nread = idx;
    }

    XPathBuf::try_from(OsStr::from_bytes(comm[..nread].trim_ascii()))
}

/// Retrieves the command line of the specified process ID (PID)
/// concatenated as a single string.
///
/// This function reads the `/proc/<pid>/cmdline` file and concatenates
/// the arguments using spaces. The function takes care of replacing null
/// bytes (`'\0'`) with spaces to format the command line as a readable string.
pub fn proc_cmdline(pid: Pid) -> Result<XPathBuf, Errno> {
    // Construct path to the appropriate cmdline file.
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"cmdline")?;

    // Safely open proc(5) file.
    let file = safe_open_proc(&path).map_err(proc_errno)?;

    // Read up to 256 bytes.
    const LIMIT: usize = 256;
    let mut data = [0u8; LIMIT];
    let nread = read_buf(file, &mut data)?;

    let mut data = data.to_vec();
    // Determine if EOF was reached or if we hit the limit
    #[expect(clippy::arithmetic_side_effects)]
    if nread <= 1 {
        // Empty cmdline.
        return Ok(XPathBuf::empty());
    } else if nread >= LIMIT - 1 {
        // Check if the last byte read is not a null byte,
        // indicating there's more data.
        if data[LIMIT - 1] != 0 {
            // Append ellipsis to indicate truncation.
            data.extend_from_slice("…".as_bytes());
        } else {
            // Remove the NUL-byte.
            data.pop();
        }
    } else {
        // If EOF was hit before the limit,
        // resize the buffer to nread - 1 (for null byte).
        data.resize(nread - 1, 0);
    }

    // Replace null bytes with spaces.
    for byte in &mut data {
        if *byte == 0 {
            *byte = b' ';
        }
    }

    Ok(data.into())
}

/// Return the system pipe max limit.
pub fn proc_pipemax() -> Result<libc::c_int, Errno> {
    proc_pipemax_read(proc_pipemax_open()?)
}

/// Open a FD to /proc/sys/fs/pipe-max-size and return a SafeOwnedFd.
pub fn proc_pipemax_open() -> Result<SafeOwnedFd, Errno> {
    safe_open_proc("sys/fs/pipe-max-size")
}

/// Retrieve the system pipe max limit from the given Fd.
pub fn proc_pipemax_read<Fd: AsFd>(fd: Fd) -> Result<libc::c_int, Errno> {
    // Read up to 24 bytes.
    let mut data = [0u8; 24];
    let nread = read_buf(fd, &mut data)?;

    btoi::<libc::c_int>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieves the value of /proc/sys/fs/file-max.
pub fn proc_fs_file_max<Fd: AsFd>(fd_proc: Fd) -> Result<u64, Errno> {
    let fd = safe_open(fd_proc, c"sys/fs/file-max", OFLAG_PROC, RFLAG_PROC)?;

    // Check the file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 bytes for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u64>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieves the value of /proc/sys/fs/nr_open.
pub fn proc_fs_nr_open<Fd: AsFd>(fd_proc: Fd) -> Result<u64, Errno> {
    let fd = safe_open(fd_proc, c"sys/fs/nr_open", OFLAG_PROC, RFLAG_PROC)?;

    // Check the file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 bytes for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u64>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieve value of /proc/sys/vm/mmap_min_addr.
pub fn proc_mmap_min_addr<Fd: AsFd>(fd_proc: Fd) -> Result<u64, Errno> {
    let fd = safe_open(fd_proc, c"sys/vm/mmap_min_addr", OFLAG_PROC, RFLAG_PROC)?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 bytes for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u64>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieve value of /proc/sys/fs/pipe-max-size.
pub fn proc_pipe_max_size<Fd: AsFd>(fd_proc: Fd) -> Result<u64, Errno> {
    let fd = safe_open(fd_proc, c"sys/fs/pipe-max-size", OFLAG_PROC, RFLAG_PROC)?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 bytes for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u64>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieve value of /proc/sys/kernel/randomize_va_space.
pub fn proc_kernel_randomize_va_space<Fd: AsFd>(fd_proc: Fd) -> Result<u8, Errno> {
    let fd = safe_open(
        fd_proc,
        c"sys/kernel/randomize_va_space",
        OFLAG_PROC,
        RFLAG_PROC,
    )?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 1 byte + 1 byte for \n.
    let mut data = [0u8; 2];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u8>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieves the value of /proc/sys/kernel/yama/ptrace_scope.
pub fn proc_yama_ptrace_scope<Fd: AsFd>(fd_proc: Fd) -> Result<u8, Errno> {
    let fd = safe_open(
        fd_proc,
        c"sys/kernel/yama/ptrace_scope",
        OFLAG_PROC,
        RFLAG_PROC,
    )?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 1 byte + 1 byte for \n.
    let mut data = [0u8; 2];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u8>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieves the value of /proc/sys/net/core/bpf_jit_enable
pub fn proc_net_bpf_jit_enable<Fd: AsFd>(fd_proc: Fd) -> Result<u8, Errno> {
    let fd = safe_open(
        fd_proc,
        c"sys/net/core/bpf_jit_enable",
        OFLAG_PROC,
        RFLAG_PROC,
    )?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 1 byte + 1 byte for \n.
    let mut data = [0u8; 2];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u8>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieves the value of /proc/sys/net/core/optmem_max.
pub fn proc_optmem_max<Fd: AsFd>(fd_proc: Fd) -> Result<usize, Errno> {
    let fd = safe_open(fd_proc, c"sys/net/core/optmem_max", OFLAG_PROC, RFLAG_PROC)?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 bytes for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    btoi::<usize>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieves the value of /proc/sys/net/core/wmem_max.
pub fn proc_wmem_max<Fd: AsFd>(fd_proc: Fd) -> Result<usize, Errno> {
    let fd = safe_open(fd_proc, c"sys/net/core/wmem_max", OFLAG_PROC, RFLAG_PROC)?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 bytes for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    btoi::<usize>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieves the value of /proc/sys/net/ipv4/ip_unprivileged_port_start.
pub fn proc_ip_unprivileged_port_start<Fd: AsFd>(fd_proc: Fd) -> Result<u16, Errno> {
    let fd = safe_open(
        fd_proc,
        c"sys/net/ipv4/ip_unprivileged_port_start",
        OFLAG_PROC,
        RFLAG_PROC,
    )?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 5 bytes + 1 byte for \n.
    let mut data = [0u8; 6];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u16>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Retrieve value of /proc/sys/net/ipv4/tcp_fastopen.
pub fn proc_tcp_fastopen<Fd: AsFd>(fd_proc: Fd) -> Result<u64, Errno> {
    let fd = safe_open(
        fd_proc,
        c"sys/net/ipv4/tcp_fastopen",
        OFLAG_PROC,
        RFLAG_PROC,
    )?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 bytes for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    btoi::<u64>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))
}

/// Return character devices registered in proc_devices(5).
pub fn proc_char_dev<Fd: AsFd>(fd_proc: Fd) -> Result<Vec<CharDevice>, Errno> {
    let file = safe_open(fd_proc, c"devices", OFLAG_PROC, RFLAG_PROC).map_err(proc_errno)?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&file).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // proc_devices(5) file is under 4 KiB.
    let mut buf = [0u8; 0x4000];
    let data = read_to_end(file, &mut buf)?;
    parse_proc_char_dev(data)
}

/// Return major of named character device from proc_devices(5).
pub fn proc_char_dev_major(name: &[u8]) -> Option<u32> {
    PROC_INFO
        .char_dev
        .iter()
        .find(|dev| dev.name.as_bytes() == name)
        .map(|dev| dev.major)
}

/// ABI known character devices for Linux >= 5.19.
pub fn proc_char_dev_abi() -> &'static [CharDevice] {
    static ABI: &[CharDevice] = &[
        CharDevice {
            major: 4,
            name: XPathCow::Borrowed(XPath::from_bytes(b"tty")),
        },
        CharDevice {
            major: 4,
            name: XPathCow::Borrowed(XPath::from_bytes(b"ttyS")),
        },
        CharDevice {
            major: 5,
            name: XPathCow::Borrowed(XPath::from_bytes(b"/dev/tty")),
        },
        CharDevice {
            major: 5,
            name: XPathCow::Borrowed(XPath::from_bytes(b"/dev/console")),
        },
        CharDevice {
            major: 5,
            name: XPathCow::Borrowed(XPath::from_bytes(b"/dev/ptmx")),
        },
        CharDevice {
            major: 136,
            name: XPathCow::Borrowed(XPath::from_bytes(b"pts")),
        },
    ];
    ABI
}

/// Reads TTY number from proc_pid_stat(5), returns character device name.
pub fn proc_tty(pid: Pid) -> Result<XPathBuf, Errno> {
    let stat = proc_stat(pid)?;
    parse_tty(stat.tty_nr, &PROC_INFO.char_dev)
}

/// Returns number of threads for the given process.
pub fn proc_task_nr(pid: Pid) -> Result<u64, Errno> {
    proc_stat(pid).map(|p| p.num_threads)
}

/// Returns number of threads for the current process.
pub fn proc_task_nr_syd() -> Result<u64, Errno> {
    proc_stat(Pid::this()).map(|p| p.num_threads)
}

/// Returns the number of processes in the system.
pub fn proc_task_nr_sys() -> Result<u64, Errno> {
    Ok(safe_sysinfo()?.process_count().into())
}

/// Checks if the number of tasks across all processes in the system
/// exceeds the given limit by inspecting the `/proc` filesystem.
/// Current process is not included into the limit.
pub fn proc_task_limit(pid: Pid, max: u64) -> Result<bool, Errno> {
    // Count tasks for the given process, return if limit hit.
    let mut count = proc_task_nr(pid)?;
    if count >= max {
        return Ok(true);
    }

    // This function is only called from main thread.
    // Hence no concurrent readdir() is possible here.
    // Rewind directory and get to work!
    let fd = PROC_FILE();
    lseek64(fd, 0, Whence::SeekSet)?;

    let this = Pid::this().as_raw();

    // Allocate a large-enough buffer to read in one go.
    let mut tasks = Vec::new();
    tasks.try_reserve(DIRENT_BUF_SIZE).or(Err(Errno::ENOMEM))?;

    // Count processes in the global /proc namespace,
    // return if limit is hit.
    loop {
        let mut entries = match getdents64(fd, DIRENT_BUF_SIZE) {
            Ok(entries) => entries,
            // ECANCELED is for EOF or empty directory.
            Err(Errno::ECANCELED | Errno::EACCES | Errno::ENOENT | Errno::EPERM | Errno::ESRCH) => {
                break
            }
            Err(errno) => return Err(errno),
        };

        #[expect(clippy::arithmetic_side_effects)]
        for entry in &mut entries {
            // PID paths are directories.
            if !entry.is_dir() {
                continue;
            }

            // Parse PID, continue on errors.
            let task = match btoi::<pid_t>(entry.name_bytes()) {
                Ok(pid) => pid,
                Err(_) => continue,
            };

            // Skip current process and the given process.
            if task == pid.as_raw() || task == this {
                continue;
            }

            // Push task to the list, return if limit is hit.
            tasks.push(task);
            count += 1;
            if count >= max {
                return Ok(true);
            }
        }
    }

    // Count tasks per-process.
    for task in tasks {
        #[expect(clippy::arithmetic_side_effects)]
        match proc_task_nr(Pid::from_raw(task)) {
            Ok(n) => count += n,
            Err(_) => continue, // task died mid-way?
        }
        if count >= max {
            return Ok(true);
        }
    }

    // If we reached here,
    // we did not hit the limit.
    Ok(false)
}

/// Parses /proc/pid/environ and returns a HashMap.
pub fn proc_environ(pid: Pid) -> Result<SydHashMap<OsString, OsString>, Errno> {
    proc_environ_read(proc_environ_open(pid)?)
}

/// Open a FD to _proc_pid_environ_(5) and return a SafeOwnedFd.
pub fn proc_environ_open(pid: Pid) -> Result<SafeOwnedFd, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"environ")?;

    safe_open_proc(&path).map_err(proc_errno)
}

/// Parses /proc/pid/environ from given Fd and returns a HashMap.
pub fn proc_environ_read(fd: SafeOwnedFd) -> Result<SydHashMap<OsString, OsString>, Errno> {
    let buf = read_all(fd)?;
    let mut map = SydHashMap::default();
    for slice in buf.split(|b| *b == 0) {
        let mut split = slice.splitn(2, |b| *b == b'=');
        if let (Some(k), Some(v)) = (split.next(), split.next()) {
            map.insert(
                OsStr::from_bytes(k).to_os_string(),
                OsStr::from_bytes(v).to_os_string(),
            );
        };
    }

    Ok(map)
}

/// Describes namespaces to which process with given PID belongs.
pub fn proc_namespaces(pid: Pid) -> Result<Namespaces, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"ns")?;
    let dirfd = proc_open(None)
        .and_then(|fd| safe_open(fd, &path, OFLAG_PROC | OFlag::O_DIRECTORY, RFLAG_PROC))
        .map_err(proc_errno)?;

    #[expect(clippy::disallowed_types)]
    let mut namespaces = std::collections::HashMap::new();
    let mut seen_dot = false;
    let mut seen_dotdot = false;
    loop {
        let mut entries = match getdents64(&dirfd, DIRENT_BUF_SIZE) {
            Ok(iter) => iter,
            Err(Errno::ECANCELED) => break, // EOF or empty directory
            Err(errno) => return Err(errno),
        };

        for entry in &mut entries {
            if !seen_dot && entry.is_dot() {
                seen_dot = true;
                continue;
            }
            if !seen_dotdot && entry.is_dotdot() {
                seen_dotdot = true;
                continue;
            }

            let (ino, dev) = statx(&dirfd, entry.as_xpath(), 0, STATX_INO).map(|stx| {
                let ino = stx.stx_ino;
                let dev = (u64::from(stx.stx_dev_major) << 32) | u64::from(stx.stx_dev_minor);
                (ino, dev)
            })?;

            let name = entry.name_bytes();
            let mut ns_path = XPathBuf::try_from("/proc")?;
            ns_path.try_push_pid(pid)?;
            ns_path.try_push(b"ns")?;
            ns_path.try_push(name)?;

            let mut typ = Vec::new();
            typ.try_reserve_exact(name.len()).or(Err(Errno::ENOMEM))?;
            typ.extend_from_slice(name);

            let mut key = Vec::new();
            key.try_reserve_exact(name.len()).or(Err(Errno::ENOMEM))?;
            key.extend_from_slice(name);

            let mut pth = Vec::new();
            pth.try_reserve_exact(ns_path.as_bytes().len())
                .or(Err(Errno::ENOMEM))?;
            pth.extend_from_slice(ns_path.as_bytes());

            let ns = Namespace {
                ns_type: OsString::from_vec(typ),
                path: OsString::from_vec(pth).into(),
                identifier: ino,
                device_id: dev,
            };

            namespaces.try_reserve(1).or(Err(Errno::ENOMEM))?;
            if namespaces.insert(OsString::from_vec(key), ns).is_some() {
                return Err(Errno::EEXIST);
            }
        }
    }

    Ok(Namespaces(namespaces))
}

/// Parses /proc/pid/net/unix, return inodes.
pub fn proc_unix_inodes(pid: Pid) -> Result<SydHashSet<u64>, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"net")?;
    path.try_push(b"unix")?;

    let file = safe_open_proc(&path).map(BufReader::new)?;
    let entries = UnixNetEntries::from_buf_read(file)
        .map(|e| e.0)
        .map_err(|err| proc_error_to_errno(&err).unwrap_or(Errno::EPERM))?;

    let mut set = SydHashSet::default();
    set.try_reserve(entries.len()).or(Err(Errno::ENOMEM))?;
    for entry in entries {
        set.insert(entry.inode);
    }

    Ok(set)
}

/// Parses /proc/pid/net/unix, return inodes and names.
#[expect(clippy::type_complexity)]
pub fn proc_unix_entries(pid: Pid) -> Result<Vec<(u64, XPathCow<'static>)>, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"net")?;
    path.try_push(b"unix")?;

    let file = safe_open_proc(&path).map(BufReader::new)?;
    let entries = UnixNetEntries::from_buf_read(file)
        .map(|e| e.0)
        .map_err(|err| proc_error_to_errno(&err).unwrap_or(Errno::EPERM))?;

    let mut vec = Vec::new();
    vec.try_reserve_exact(entries.len())
        .or(Err(Errno::ENOMEM))?;

    for entry in entries {
        let name = match entry.path {
            Some(path) => XPathCow::Owned(path.into()),
            None => XPathCow::Borrowed(XPath::from_bytes(b"!unnamed")),
        };
        vec.push((entry.inode, name));
    }

    Ok(vec)
}

/// Sets the AT_SECURE value to 1 in the auxiliary vector of the
/// specified process.
///
/// This function locates the auxiliary vector in the target process's
/// memory and sets the AT_SECURE entry to 1. It uses the
/// `/proc/pid/stat` file to get the address of the start of the stack
/// and parses the stack according to the standard Linux process stack
/// layout.
///
/// # Arguments
///
/// * `pid` - The PID of the target process.
/// * `elf_type` - The ELF type (Elf32 or Elf64) of the target process.
/// * `deny_vdso` - True to deny access to vDSO by overwriting AT_SYSINFO{,_EHDR}.
///
/// # Returns
///
/// Returns `Ok(())` on success, or an `Err(Errno)` if an error occurs.
pub fn proc_set_at_secure(pid: Pid, elf_type: ElfType, deny_vdso: bool) -> Result<(), Errno> {
    // This function requires CONFIG_CROSS_MEMORY_ATTACH,
    // unless Syd is explicitly configured to fallback.
    let mut proc_mem = if Sandbox::use_proc_pid_mem() {
        let mut path = XPathBuf::from_pid(pid)?;
        path.try_push(b"mem")?;

        let mut flags = OFLAG_PROC;
        flags.remove(OFlag::O_RDONLY);
        flags.insert(OFlag::O_RDWR);
        Some(safe_open(PROC_FILE(), &path, flags, RFLAG_PROC).map_err(proc_errno)?)
    } else {
        None
    };

    fn proc_read(
        proc_mem: Option<&mut SafeOwnedFd>,
        pid: Pid,
        buf: &mut [u8],
        base_addr: usize,
    ) -> Result<usize, Errno> {
        match proc_mem {
            Some(fd) => {
                fd.seek(SeekFrom::Start(base_addr as u64))
                    .map_err(|err| err2no(&err))?;
                read_buf(fd, buf)
            }
            None => {
                let local_len = buf.len();
                let mut local_iov = [IoSliceMut::new(buf)];
                let remote_iov = [RemoteIoVec {
                    base: base_addr,
                    len: local_len,
                }];
                process_vm_readv(pid, &mut local_iov, &remote_iov)
            }
        }
    }

    fn proc_write(
        proc_mem: Option<&mut SafeOwnedFd>,
        pid: Pid,
        buf: &[u8],
        base_addr: usize,
    ) -> Result<usize, Errno> {
        match proc_mem {
            Some(fd) => {
                fd.seek(SeekFrom::Start(base_addr as u64))
                    .map_err(|err| err2no(&err))?;

                let mut nwrite = 0;
                while nwrite < buf.len() {
                    match retry_on_eintr(|| safe_write(&*fd, &buf[nwrite..]))? {
                        0 => break,
                        n => nwrite = nwrite.checked_add(n).ok_or(Errno::EOVERFLOW)?,
                    }
                }

                Ok(nwrite)
            }
            None => {
                let local_len = buf.len();
                let local_iov = [IoSlice::new(buf)];
                let remote_iov = [RemoteIoVec {
                    base: base_addr,
                    len: local_len,
                }];
                process_vm_writev(pid, &local_iov, &remote_iov)
            }
        }
    }

    // Get the address of the start of the stack for the process.
    let sp = proc_stack_start(pid)?;
    let sp = usize::try_from(sp).or(Err(Errno::EFAULT))?;

    let (sizeof_ptr, sizeof_ptr2) = match elf_type {
        ElfType::Elf32 => (4, 8),
        ElfType::Elf64 => (8, 16),
    };

    let mut offset = 0usize;

    // Read argc (the argument count).
    let mut buf = [0u8; 8]; // Max size needed for usize.
    let bytes_read = proc_read(proc_mem.as_mut(), pid, &mut buf[..sizeof_ptr], sp)?;
    if bytes_read != sizeof_ptr {
        return Err(Errno::EIO);
    }

    // SAFETY: Ensure argc is not zero.
    // The Linux kernel has a mitigation for this since version 5.18.
    // Syd is recommended to run on Linux-5.19 or later but technically
    // it is possible to run it on Linux-5.0 or later so we include the
    // check here for defense in depth.
    // See:
    // https://github.com/torvalds/linux/blob/88d324e69ea9f3ae1c1905ea75d717c08bdb8e15/fs/exec.c#L1962
    // https://lwn.net/Articles/882799/
    // https://blog.qualys.com/vulnerabilities-threat-research/2022/01/25/pwnkit-local-privilege-escalation-vulnerability-discovered-in-polkits-pkexec-cve-2021-4034
    let argc = read_usize_from_ne_bytes(&buf[..sizeof_ptr], sizeof_ptr)?;
    if argc == 0 {
        return Err(Errno::EINVAL);
    }

    offset = offset.checked_add(sizeof_ptr).ok_or(Errno::EINVAL)?;

    // Skip over argv pointers (argc pointers plus a NULL terminator).
    let argv_size = argc
        .checked_add(1)
        .ok_or(Errno::EINVAL)?
        .checked_mul(sizeof_ptr)
        .ok_or(Errno::EINVAL)?;
    offset = offset.checked_add(argv_size).ok_or(Errno::EINVAL)?;

    // Skip over envp pointers until NULL terminator is found.
    loop {
        // Read one pointer at a time.
        let mut envp_buf = [0u8; 8];
        let bytes_read = proc_read(
            proc_mem.as_mut(),
            pid,
            &mut envp_buf[..sizeof_ptr],
            sp.checked_add(offset).ok_or(Errno::EINVAL)?,
        )?;
        if bytes_read != sizeof_ptr {
            return Err(Errno::EIO);
        }
        let envp_ptr = read_usize_from_ne_bytes(&envp_buf[..sizeof_ptr], sizeof_ptr)?;
        offset = offset.checked_add(sizeof_ptr).ok_or(Errno::EINVAL)?;
        if envp_ptr == 0 {
            break;
        }
    }

    // Read the auxiliary vector into a buffer starting from the current
    // offset. Technically ~256 bytes should be enough to locate
    // AT_SECURE because an auxv entry is at most 16 bytes (8 bytes on
    // 32-bit), and AT_SECURE is roughly the 16th on the list but we
    // leave a bit more room for safety and future-compat. Check
    // fs/exec.c in kernel sources for more information.
    const READ_SIZE: usize = 512; // Read up to 512 bytes.
    let mut buf = [0u8; READ_SIZE];
    let sp = sp.checked_add(offset).ok_or(Errno::EINVAL)?;
    let bytes_read = proc_read(proc_mem.as_mut(), pid, &mut buf, sp)?;
    if bytes_read == 0 {
        return Err(Errno::EIO);
    }

    // Now parse the auxiliary vector.
    // For added validation, we ensure we have the sequence of keys:
    // AT_UID -> AT_EUID -> AT_GID -> AT_EGID -> AT_SECURE
    // We also ensure no other key is ever present in this sequence.
    // The AT_NULL key indicates the end of the vector.
    #[expect(clippy::cast_possible_truncation)]
    const AT_NULL: usize = libc::AT_NULL as usize;
    #[expect(clippy::cast_possible_truncation)]
    const AT_UID: usize = libc::AT_UID as usize;
    #[expect(clippy::cast_possible_truncation)]
    const AT_EUID: usize = libc::AT_EUID as usize;
    #[expect(clippy::cast_possible_truncation)]
    const AT_GID: usize = libc::AT_GID as usize;
    #[expect(clippy::cast_possible_truncation)]
    const AT_EGID: usize = libc::AT_EGID as usize;
    #[expect(clippy::cast_possible_truncation)]
    const AT_SECURE: usize = libc::AT_SECURE as usize;
    const AT_REQKEY: &[usize] = &[AT_UID, AT_EUID, AT_GID, AT_EGID, AT_SECURE];
    let mut required_index = 0;

    // Used to deny access to vDSO as necessary.
    //
    // 1. libc crate does not define these for all arches we support,
    //    however the values are consistent across all.
    // 2. AT_SECURE comes after AT_SYSINFO{,_EHDR} in the auxiliary vector.
    const AT_SYSINFO: usize = 32;
    const AT_SYSINFO_EHDR: usize = 33;

    // Store the UID/GID values for comparison.
    // We're going to check these values against ours
    // and fail as necessary.
    let mut at_uid_val = None;
    let mut at_euid_val = None;
    let mut at_gid_val = None;
    let mut at_egid_val = None;

    offset = 0;
    loop {
        // Determine key and value location, and check it's within bounds.
        let key_end = offset.checked_add(sizeof_ptr).ok_or(Errno::EINVAL)?;
        let val_end = key_end.checked_add(sizeof_ptr).ok_or(Errno::EINVAL)?;
        if val_end > bytes_read {
            break;
        }

        // Read key and value from the buffer.
        let key = read_usize_from_ne_bytes(&buf[offset..key_end], sizeof_ptr)?;
        let val = read_usize_from_ne_bytes(&buf[key_end..val_end], sizeof_ptr)?;

        if key == AT_REQKEY[required_index] {
            // Key matches the expected key in sequence.
            match key {
                AT_UID => at_uid_val = Some(val),
                AT_EUID => at_euid_val = Some(val),
                AT_GID => at_gid_val = Some(val),
                AT_EGID => at_egid_val = Some(val),
                _ => {}
            }

            required_index = required_index.checked_add(1).ok_or(Errno::EINVAL)?;
            if required_index >= AT_REQKEY.len() {
                // We've found the sequence ending with AT_SECURE!

                // Verify that the UID/GID values match ours.
                let uid = Uid::current().as_raw() as usize;
                let euid = Uid::effective().as_raw() as usize;
                let gid = Gid::current().as_raw() as usize;
                let egid = Gid::effective().as_raw() as usize;

                if at_uid_val != Some(uid)
                    || at_euid_val != Some(euid)
                    || at_gid_val != Some(gid)
                    || at_egid_val != Some(egid)
                {
                    // SAFETY:
                    // 1. Change return success.
                    // 2. Going and coming without error.
                    // 3. Action brings good fortune.
                    return Err(Errno::EPERM);
                }

                // Only modify AT_SECURE, if it's not already set.
                // SAFETY: We do this check only after UID/GID verification.
                if val != 0 {
                    return Ok(());
                }

                // Overwrite the value in the local buffer.
                let val = usize_to_ne_bytes(1, sizeof_ptr);
                buf[key_end..val_end].copy_from_slice(&val);

                // SAFETY: We have verified that the auxiliary vector
                // contains the expected keys in the correct order, and
                // that the UID/GID values match our own. This ensures
                // that we are modifying a trusted process. We also
                // ensure that the offsets are within the bounds of the
                // read buffer, preventing overflows.
                //
                // Write the modified value back to the target process.
                if proc_write(
                    proc_mem.as_mut(),
                    pid,
                    &buf[key_end..val_end],
                    sp.checked_add(key_end).ok_or(Errno::EINVAL)?,
                )? != sizeof_ptr
                {
                    return Err(Errno::EIO);
                }

                // All done, return success.
                return Ok(());
            }
        } else if required_index > 0 {
            // An unexpected key appeared; validation fails!
            return Err(Errno::EPERM);
        } else if deny_vdso && (key == AT_SYSINFO || key == AT_SYSINFO_EHDR) {
            // Deny access to vDSO as requested.
            // AT_SYS_INFO{,_EHDR} always comes before AT_SECURE.
            //
            // Overwrite the key and value in the local buffer:
            // Overwrite the key with AT_SECURE.
            // Overwrite the value with 1.
            let key = usize_to_ne_bytes(AT_SECURE, sizeof_ptr);
            let val = usize_to_ne_bytes(1, sizeof_ptr);
            buf[offset..key_end].copy_from_slice(&key);
            buf[key_end..val_end].copy_from_slice(&val);

            // Write the modified value back to the target process.
            if proc_write(
                proc_mem.as_mut(),
                pid,
                &buf[offset..val_end],
                sp.checked_add(offset).ok_or(Errno::EINVAL)?,
            )? != sizeof_ptr2
            {
                return Err(Errno::EIO);
            }
        } else if key == AT_NULL {
            break;
        }

        // SAFETY: We check for arithmetic overflow when advancing the
        // offset to prevent wrapping around.
        offset = offset.checked_add(sizeof_ptr2).ok_or(Errno::EINVAL)?;
    }

    Err(Errno::ENOENT)
}

/// List `/proc/pid/fd` contents.
///
/// Return a vector of `(RawFd, XPathBuf)` tuples, where each `RawFd`
/// is the file descriptor number and the `XPathBuf` is the path it points to.
///
/// Useful for debugging file descriptor leaks.
#[expect(clippy::type_complexity)]
pub fn proc_pid_fd(pid: Option<Pid>) -> Result<Vec<(RawFd, XPathBuf)>, Errno> {
    let pid = pid.unwrap_or_else(getpid);

    let mut dir = XPathBuf::from_pid(pid)?;
    dir.try_push(b"fd")?;

    let dir = safe_open(
        PROC_FILE(),
        &dir,
        OFLAG_PROC | OFlag::O_DIRECTORY,
        RFLAG_PROC,
    )?;

    let mut res = vec![];
    let mut seen_dot = false;
    let mut seen_dotdot = false;
    loop {
        let mut entries = match getdents64(&dir, DIRENT_BUF_SIZE) {
            Ok(entries) => entries,
            Err(Errno::ECANCELED) => break, // EOF or empty directory
            Err(errno) => return Err(errno),
        };

        for entry in &mut entries {
            if !seen_dot && entry.is_dot() {
                seen_dot = true;
                continue;
            }
            if !seen_dotdot && entry.is_dotdot() {
                seen_dotdot = true;
                continue;
            }
            let entry = XPath::from_bytes(entry.name_bytes());
            let fd = parse_fd(entry)?;
            let target = readlinkat(&dir, entry)?;

            res.push((fd, target));
        }
    }

    Ok(res)
}

/// Return the max open files soft limit for the given process.
pub fn proc_max_open_files(pid: Pid) -> Result<LimitValue, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"limits")?;

    // Safely open proc(5) file.
    let file = safe_open_proc(&path)?;

    let mut buf = [0; 1792]; // A typical limits file is about 1500 bytes.
    map_result(parse_max_open_files(read_to_end(file, &mut buf)?))
}

/// Return a random fd slot for the sandbox process.
pub fn proc_rand_fd(pid: Pid) -> Result<RawFd, Errno> {
    // SAFETY: Cap to a sane maximum because sufficiently
    // big values of the hard limit tend to return ENOMEM.
    const OFILE_MAX: u64 = 0x10000;
    let range_start = 7u64;
    let range_end = match proc_max_open_files(pid)? {
        LimitValue::Unlimited => OFILE_MAX,
        LimitValue::Value(val) => val.saturating_sub(1).min(OFILE_MAX),
    };

    if range_end <= range_start {
        return Err(Errno::EMFILE);
    }

    let range = range_start..=range_end;

    for _ in range.clone() {
        let fd_rand = randint(range.clone())? as RawFd;

        // Check if the slot is free.
        // This is subject to race, and optimally should
        // be implemented in the host Linux kernel.
        return match is_open_fd(pid, fd_rand) {
            Ok(true) => continue,
            Ok(false) => Ok(fd_rand),
            Err(errno) => Err(errno),
        };
    }

    Err(Errno::EBADF)
}

/// Log `/proc/self/fd` contents.
///
/// Useful for debugging file descriptor leaks.
pub fn log_proc_pid_fd(pid: Option<Pid>) -> Result<(), Errno> {
    let fds = proc_pid_fd(pid)?;
    let pid = pid.unwrap_or_else(getpid);

    crate::error!("ctx": "log_proc_self_fd",
        "msg": xfmt!("List of /proc/{pid}/fd"),
        "fds": fds, "pid": pid.as_raw());

    Ok(())
}

/// Kernel taint strings.
///
/// See: https://docs.kernel.org/admin-guide/tainted-kernels.html#table-for-decoding-tainted-state
pub static KERNEL_TAINT_STRINGS: [&str; 20] = [
    "P (Proprietary module was loaded)",
    "F (Module was force loaded)",
    "S (Kernel running on an out of specification system)",
    "R (Module was force unloaded)",
    "M (Processor reported a Machine Check Exception)",
    "B (Bad page referenced or unexpected page flags)",
    "U (Taint requested by userspace application)",
    "D (Kernel died recently: OOPS/BUG)",
    "A (ACPI table overridden by user)",
    "W (Kernel issued warning)",
    "C (Staging driver was loaded)",
    "I (Workaround for bug in platform firmware applied)",
    "O (Externally-built \"out-of-tree\" module was loaded)",
    "E (Unsigned module was loaded)",
    "L (Soft lockup occurred)",
    "K (Kernel has been live patched)",
    "X (Auxiliary taint, used by distros)",
    "T (Kernel built with struct randomization plugin)",
    "N (An in-kernel test has been run)",
    "J (Userspace used a mutating debug operation in fwctl)",
];

bitflags! {
    /// Bitflags for `/proc/sys/kernel/tainted`.
    #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
    pub struct KernelTaintFlags: u64 {
        /// Proprietary module was loaded
        const PROPRIETARY_MODULE = 1 << 0; // P
        /// Module was force loaded
        const MODULE_FORCE_LOADED = 1 << 1; // F
        /// Kernel running on an out of specification system
        const OUT_OF_SPEC_SYSTEM = 1 << 2; // S
        /// Module was force unloaded
        const MODULE_FORCE_UNLOADED = 1 << 3; // R
        /// Processor reported a Machine Check Exception
        const MACHINE_CHECK_EXCEPTION = 1 << 4; // M
        /// Bad page referenced or unexpected page flags
        const BAD_PAGE_REFERENCE = 1 << 5; // B
        /// Taint requested by userspace application
        const USER_REQUEST = 1 << 6; // U
        /// Kernel died recently: OOPS/BUG
        const OOPS_OR_BUG = 1 << 7; // D
        /// ACPI table overridden by user
        const ACPI_TABLE_OVERRIDDEN = 1 << 8; // A
        /// Kernel issued warning
        const WARNING_ISSUED = 1 << 9; // W
        /// Staging driver was loaded
        const STAGING_DRIVER_LOADED = 1 << 10; // C
        /// Workaround for bug in platform firmware applied
        const WORKAROUND_FW_BUG = 1 << 11; // I
        /// Externally-built "out-of-tree" module was loaded
        const OUT_OF_TREE_MODULE = 1 << 12; // O
        /// Unsigned module was loaded
        const UNSIGNED_MODULE_LOADED = 1 << 13; // E
        /// Soft lockup occurred
        const SOFT_LOCKUP_OCCURRED = 1 << 14; // L
        /// Kernel has been live patched
        const LIVE_PATCHED = 1 << 15; // K
        /// Auxiliary taint, used by distros
        const AUXILIARY = 1 << 16; // X
        /// Kernel built with struct randomization plugin
        const BUILT_WITH_RANDOMIZATION = 1 << 17; // T
        /// An in-kernel test has been run
        const IN_KERNEL_TEST_RUN = 1 << 18; // N
        /// Userspace used a mutating debug operation in fwctl
        const FWCTL_DEBUG_WRITE_USED = 1 << 19; // J
    }
}

impl KernelTaintFlags {
    /// Returns taint reasons (verbatim) for set bits 0..=19.
    pub fn reasons(self) -> impl Iterator<Item = &'static str> + 'static {
        (0..KERNEL_TAINT_STRINGS.len())
            .filter(move |bit| self.bits() & (1u64 << bit) != 0)
            .map(|bit| KERNEL_TAINT_STRINGS[bit])
    }

    /// True if *no* bits are set (bitfield == 0).
    pub fn is_clean(self) -> bool {
        self.is_empty()
    }
}

impl fmt::Display for KernelTaintFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_clean() {
            write!(f, "Kernel is not tainted (0).")
        } else {
            write!(
                f,
                "Kernel is tainted: {}.",
                self.reasons().collect::<Vec<_>>().join(", ")
            )
        }
    }
}

/// Retrieves the value of /proc/sys/kernel/tainted as KernelTaintFlags.
pub fn proc_kernel_taint<Fd: AsFd>(fd_proc: Fd) -> Result<KernelTaintFlags, Errno> {
    let fd = safe_open(fd_proc, c"sys/kernel/tainted", OFLAG_PROC, RFLAG_PROC)?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    // Read up to 24 bytes + 1 byte for \n.
    let mut data = [0u8; 25];
    let nread = read_buf(fd, &mut data)?;

    // Parse decimal -> u64, then map to flags (retain unknown higher bits).
    let val = btoi::<u64>(data[..nread].trim_ascii()).map_err(|err| btoi2err(&err))?;
    Ok(KernelTaintFlags::from_bits_retain(val))
}

/// Set max PID limit for PID namespace.
pub fn proc_pid_max<Fd: AsFd>(fd_proc: Fd, pid_max: u64) -> Result<(), Errno> {
    let mut buf = itoa::Buffer::new();
    let pid_max = buf.format(pid_max).as_bytes();
    proc_write(&fd_proc, b"sys/kernel/pid/max", pid_max, false /*pid*/)
}

/// Set up user mappings for user namespace.
pub fn proc_map_user<Fd: AsFd>(
    fd_proc: Fd,
    uid: Uid,
    gid: Gid,
    map_root: bool,
) -> Result<(), Errno> {
    let uid_map = {
        let mut buf = Vec::new();
        write!(
            &mut buf,
            "{} {uid} 1",
            if map_root { 0 } else { uid.as_raw() }
        )
        .map_err(|err| err2no(&err))?;
        buf
    };

    let gid_map = {
        let mut buf = Vec::new();
        write!(
            &mut buf,
            "{} {gid} 1",
            if map_root { 0 } else { gid.as_raw() }
        )
        .map_err(|err| err2no(&err))?;
        buf
    };

    // Write "deny" to /proc/self/setgroups before writing to gid_map.
    proc_write(&fd_proc, b"setgroups", b"deny", true /*pid*/)?;

    // Write GID mapping to gid_map.
    proc_write(&fd_proc, b"gid_map", &gid_map, true /*pid*/)?;

    // Write UID mapping to uid map.
    proc_write(&fd_proc, b"uid_map", &uid_map, true /*pid*/)?;

    Ok(())
}

/// Set up time offsets for time namespace.
pub fn proc_set_time<Fd: AsFd>(fd_proc: Fd, boffset: i64, moffset: i64) -> Result<(), Errno> {
    // <clock-id> <offset-secs> <offset-nanosecs>
    let mut buf = itoa::Buffer::new();
    let mut data = "monotonic ".to_string();
    data.push_str(buf.format(moffset));
    data.push_str(" 0\nboottime ");
    data.push_str(buf.format(boffset));
    data.push_str(" 0\n");

    proc_write(
        fd_proc,
        b"timens_offsets",
        data.as_bytes(),
        true, /*pid*/
    )
}

/// Set OOM score adjustment of calling process.
#[cfg(feature = "oci")]
pub fn proc_oom_score_adj(score: i32) -> Result<(), Errno> {
    let fd_proc = proc_open(None)?;
    let mut buf = itoa::Buffer::new();
    let score = buf.format(score).as_bytes();
    proc_write(fd_proc, b"oom_score_adj", score, true /*pid*/)
}

// Write the given $data to /proc/$pid/$name.
fn proc_write<Fd: AsFd>(fd_proc: Fd, name: &[u8], data: &[u8], pid: bool) -> Result<(), Errno> {
    let pfd = if pid {
        let mut pfd = XPathBuf::from_pid(Pid::this())?;
        pfd.try_push(name)?;
        XPathCow::Owned(pfd)
    } else {
        XPathCow::Borrowed(XPath::from_bytes(name))
    };

    // Open proc file safely.
    let fd = safe_open(
        fd_proc,
        pfd.as_ref(),
        OFlag::O_WRONLY,
        ResolveFlag::RESOLVE_NO_XDEV,
    )?;

    // Check file is an empty file or bail out.
    if !is_empty_file(&fd).unwrap_or(false) {
        return Err(Errno::EBADFD);
    }

    write_all(&fd, data)
}

/// Open /proc safely and validate proc(5)
///
/// This function is safe to call before syd::config::proc_init.
pub fn proc_open(proc_mountpoint: Option<&XPath>) -> Result<SafeOwnedFd, Errno> {
    let mnt = proc_mountpoint.unwrap_or(XPath::from_bytes(b"/proc"));
    let how = OpenHow::new()
        .flags(OFlag::O_PATH | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC)
        .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS | ResolveFlag::RESOLVE_NO_SYMLINKS);
    #[expect(clippy::disallowed_methods)]
    let fd_proc = openat2(AT_BADFD, mnt, how)?;

    // SAFETY: Validate what we've opened is proc(5).
    if !is_proc(&fd_proc).unwrap_or(false) {
        return Err(Errno::EXDEV);
    }

    Ok(fd_proc)
}

#[cfg(feature = "kcov")]
pub(crate) fn proc_kcov_read_id(tid: Pid, fd: RawFd) -> Result<crate::kcov::KcovId, Errno> {
    if tid.as_raw() < 1 {
        return Err(Errno::EINVAL);
    }

    if fd < 0 {
        return Err(Errno::EBADF);
    }

    let pfd = XPathBuf::from_pid_fd(tid, fd)?;

    statx(PROC_FILE(), &pfd, 0, STATX_INO)
        .map(|statx| statx.stx_ino)
        .map(crate::kcov::KcovId::new)
}

#[cfg(test)]
pub(crate) mod tests {
    use nix::{
        sched::CloneFlags,
        sys::{
            signal::{
                raise, sigaction, SaFlags, SigAction, SigHandler, SigSet, SigmaskHow, Signal,
            },
            stat::umask,
            wait::{Id, WaitPidFlag},
        },
    };

    use super::*;
    use crate::{
        compat::{waitid, WaitStatus},
        fd::{fdclone, pidfd_open},
        fs::tgkill,
    };

    // Setup function to open static proc fd.
    pub(crate) fn setup() -> bool {
        let _ = crate::log::log_init_simple(crate::syslog::LogLevel::Warn);

        if let Err(errno) = crate::fd::open_static_proc(OFlag::O_PATH) {
            eprintln!("Failed to initialize proc: {errno}!");
            return false;
        }

        true
    }

    // Signal helpers
    //
    // SAFETY: sigaction(2) is needed for signal-based tests.
    //
    // Install a no-op handler for `sig`, return the old action.
    #[expect(unsafe_code)]
    fn sig_catch(sig: Signal) -> Result<SigAction, Errno> {
        extern "C" fn noop_handler(_: libc::c_int) {}

        let sa = SigAction::new(
            SigHandler::Handler(noop_handler),
            SaFlags::empty(),
            SigSet::empty(),
        );
        unsafe { sigaction(sig, &sa) }
    }

    // Set SIG_DFL for `sig`, return the old action.
    #[expect(unsafe_code)]
    fn sig_default(sig: Signal) -> Result<SigAction, Errno> {
        let sa = SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty());
        unsafe { sigaction(sig, &sa) }
    }

    // Restore a saved sigaction.
    #[expect(unsafe_code)]
    fn sig_restore(sig: Signal, old: &SigAction) -> Result<(), Errno> {
        unsafe { sigaction(sig, old) }?;
        Ok(())
    }

    // Block `sig` on the current thread, return the old mask.
    fn sig_block(sig: Signal) -> Result<SigSet, Errno> {
        let mut set = SigSet::empty();
        set.add(sig);
        set.thread_swap_mask(SigmaskHow::SIG_BLOCK)
    }

    // Restore a saved signal mask on the current thread.
    fn sig_setmask(set: &SigSet) -> Result<(), Errno> {
        set.thread_set_mask()
    }

    // Make proc_pid_auxv(5) buffer from the given entries.
    fn make_auxv(entries: &[(usize, usize)], width: usize) -> Vec<u8> {
        let mut buf = Vec::new();
        for &(k, v) in entries {
            buf.extend_from_slice(&usize_to_ne_bytes(k, width));
            buf.extend_from_slice(&usize_to_ne_bytes(v, width));
        }
        buf.extend_from_slice(&usize_to_ne_bytes(0, width));
        buf.extend_from_slice(&usize_to_ne_bytes(0, width));
        buf
    }

    #[test]
    fn test_proc_errno_1() {
        assert_eq!(proc_errno(Errno::ENOENT), Errno::ESRCH);
    }

    #[test]
    fn test_proc_errno_2() {
        assert_eq!(proc_errno(Errno::EPERM), Errno::EPERM);
    }

    #[test]
    fn test_proc_errno_3() {
        assert_eq!(proc_errno(Errno::EACCES), Errno::EACCES);
    }

    #[test]
    fn test_read_usize_from_ne_bytes_1() {
        let val: u32 = 0x12345678;
        let bytes = val.to_ne_bytes();
        let result = read_usize_from_ne_bytes(&bytes, 4).unwrap();
        assert_eq!(result, 0x12345678);
    }

    #[test]
    fn test_read_usize_from_ne_bytes_2() {
        let val: u64 = 0x0000_0001_0000_0000;
        let bytes = val.to_ne_bytes();
        let result = read_usize_from_ne_bytes(&bytes, 8).unwrap();
        assert_eq!(result as u64, 0x0000_0001_0000_0000);
    }

    #[test]
    fn test_read_usize_from_ne_bytes_3() {
        let bytes = [0u8; 3];
        assert_eq!(read_usize_from_ne_bytes(&bytes, 4), Err(Errno::EFAULT));
    }

    #[test]
    fn test_read_usize_from_ne_bytes_4() {
        let bytes = [0u8; 7];
        assert_eq!(read_usize_from_ne_bytes(&bytes, 8), Err(Errno::EFAULT));
    }

    #[test]
    fn test_read_usize_from_ne_bytes_5() {
        let bytes = [0u8; 16];
        assert_eq!(read_usize_from_ne_bytes(&bytes, 3), Err(Errno::EINVAL));
    }

    #[test]
    fn test_usize_to_ne_bytes_1() {
        let bytes = usize_to_ne_bytes(0x42, 4);
        assert_eq!(bytes.len(), 4);
        assert_eq!(bytes, (0x42u32).to_ne_bytes().to_vec());
    }

    #[test]
    fn test_usize_to_ne_bytes_2() {
        let bytes = usize_to_ne_bytes(0x42, 8);
        assert_eq!(bytes.len(), 8);
        assert_eq!(bytes, (0x42u64).to_ne_bytes().to_vec());
    }

    #[test]
    fn test_usize_to_ne_bytes_3() {
        let original: usize = 12345;
        let bytes = usize_to_ne_bytes(original, std::mem::size_of::<usize>());
        let recovered = read_usize_from_ne_bytes(&bytes, std::mem::size_of::<usize>()).unwrap();
        assert_eq!(recovered, original);
    }

    #[test]
    fn test_proc_tgid_1() {
        if !setup() {
            return;
        }

        let result = proc_tgid(Pid::from_raw(i32::MAX));
        assert!(result.is_err(), "{result:?}");
    }

    #[test]
    fn test_proc_umask_1() {
        if !setup() {
            return;
        }

        let result = proc_umask(Pid::from_raw(i32::MAX));
        assert!(result.is_err(), "{result:?}");
    }

    #[test]
    fn test_proc_umask_2() {
        if !setup() {
            return;
        }

        // This test sets various umask values and then checks if our function correctly identifies them.
        let umasks = [
            Mode::from_bits_truncate(0o0000),
            Mode::from_bits_truncate(0o0002),
            Mode::from_bits_truncate(0o0022),
            Mode::from_bits_truncate(0o0077),
            Mode::from_bits_truncate(0o0777),
        ];

        for &my_umask in &umasks {
            umask(my_umask);
            let result = proc_umask(Pid::this()).unwrap();
            assert_eq!(result, my_umask, "{result:o} != {my_umask:o}");
        }

        // Resetting the umask to a default value after test
        umask(Mode::from_bits_truncate(0o0022));
    }

    #[test]
    fn test_proc_pidfd_get_tgid_1() {
        if !setup() {
            return;
        }

        let mypid = getpid();
        let pidfd = pidfd_open(mypid, 0).unwrap();
        let retpid = proc_pidfd_get_tgid(pidfd).unwrap();
        assert_eq!(mypid, retpid);
    }

    #[test]
    fn test_proc_interrupt_1() -> Result<(), Errno> {
        if !setup() {
            return Ok(());
        }

        // Caught + blocked + pending signal is excluded from interrupt
        // set, and vanishes after delivery.
        let sig = Signal::SIGUSR1;
        let signo = sig as libc::c_int;
        let tid = gettid();

        let old_sa = sig_catch(sig)?;
        let old_mask = sig_block(sig)?;
        raise(sig)?;

        let status = proc_status(tid)?;
        if !status.sig_pending_thread.contains(signo) {
            return Err(Errno::EINVAL);
        }
        if !status.sig_blocked.contains(signo) {
            return Err(Errno::EINVAL);
        }
        if !status.sig_caught.contains(signo) {
            return Err(Errno::EINVAL);
        }

        let sigset = proc_interrupt(tid)?;
        if sigset.contains(signo) {
            return Err(Errno::EINVAL);
        }

        sig_setmask(&old_mask)?;

        let status2 = proc_status(tid)?;
        if status2.sig_pending_thread.contains(signo) {
            return Err(Errno::EINVAL);
        }

        let sigset2 = proc_interrupt(tid)?;
        if sigset2.contains(signo) {
            return Err(Errno::EINVAL);
        }

        sig_restore(sig, &old_sa)?;
        Ok(())
    }

    #[test]
    fn test_proc_interrupt_2() -> Result<(), Errno> {
        if !setup() {
            return Ok(());
        }

        // Uncaught (SIG_DFL) + blocked + pending signal is excluded
        // from interrupt set.
        let sig = Signal::SIGUSR2;
        let signo = sig as libc::c_int;
        let tid = gettid();

        let old_sa = sig_default(sig)?;
        let old_mask = sig_block(sig)?;
        raise(sig)?;

        let status = proc_status(tid)?;
        if !status.sig_pending_thread.contains(signo) {
            return Err(Errno::EINVAL);
        }
        if !status.sig_blocked.contains(signo) {
            return Err(Errno::EINVAL);
        }
        if status.sig_caught.contains(signo) {
            return Err(Errno::EINVAL);
        }

        let sigset = proc_interrupt(tid)?;
        if sigset.contains(signo) {
            return Err(Errno::EINVAL);
        }

        sig_catch(sig)?;
        sig_setmask(&old_mask)?;

        sig_restore(sig, &old_sa)?;
        Ok(())
    }

    #[test]
    #[expect(unsafe_code)]
    fn test_proc_interrupt_3() -> Result<(), Errno> {
        if !setup() {
            return Ok(());
        }

        // Caught + blocked + pending signal in a cloned child is
        // excluded from interrupt set.
        let sig = Signal::SIGUSR1;
        let signo = sig as libc::c_int;

        let (pidfd, _) = fdclone(
            || {
                let errno = (|| -> Result<(), Errno> {
                    sig_catch(sig)?;
                    sig_block(sig)?;

                    let pid = getpid();
                    tgkill(pid, pid, signo)?;

                    let status = proc_status(getpid())?;
                    if !status.sig_pending_thread.contains(signo) {
                        return Err(Errno::EINVAL);
                    }
                    if !status.sig_blocked.contains(signo) {
                        return Err(Errno::EINVAL);
                    }
                    if !status.sig_caught.contains(signo) {
                        return Err(Errno::EINVAL);
                    }

                    let sigset = proc_interrupt(getpid())?;
                    if sigset.contains(signo) {
                        return Err(Errno::EINVAL);
                    }

                    Ok(())
                })();

                unsafe { libc::_exit(errno.map_or_else(|e| e as i32, |()| 0)) }
            },
            CloneFlags::empty(),
            Some(libc::SIGCHLD),
        )?;

        match waitid(Id::PIDFd(pidfd.as_fd()), WaitPidFlag::WEXITED)? {
            WaitStatus::Exited(_, 0) => Ok(()),
            WaitStatus::Exited(_, code) => Err(Errno::from_raw(code)),
            _ => Err(Errno::ECHILD),
        }
    }

    #[test]
    fn test_parse_stack_pointer_1() {
        let data = b"62 0x1 0x7fffffffca30 0x400 0x0 0x0 0x0 0x7fffffffcf50 0x7ffff7e30a2c\n";
        assert_eq!(parse_stack_pointer(data).unwrap(), 0x7fffffffcf50);
    }

    #[test]
    fn test_parse_stack_pointer_2() {
        let data = b"-1 0x7fffffffd070 0x7ffff7e30a2c\n";
        assert_eq!(parse_stack_pointer(data).unwrap(), 0x7fffffffd070);
    }

    #[test]
    fn test_parse_stack_pointer_3() {
        let data = b"running\n";
        assert_eq!(parse_stack_pointer(data).unwrap_err(), Errno::EBUSY);
    }

    #[test]
    fn test_parse_auxv_1() {
        assert!(parse_auxv(&[], true).unwrap().is_empty());
        assert!(parse_auxv(&[], false).unwrap().is_empty());
    }

    #[test]
    fn test_parse_auxv_2() {
        let entries = [(3, 0x40_0040), (9, 0x40_1000), (25, 0x7fff_ffff_d749)];
        let buf = make_auxv(&entries, 8);
        let m = parse_auxv(&buf, false).unwrap();
        assert_eq!(m.get(&3), Some(&0x40_0040));
        assert_eq!(m.get(&9), Some(&0x40_1000));
        assert_eq!(m.get(&25), Some(&0x7fff_ffff_d749));
        assert_eq!(m.len(), 3);
    }

    #[test]
    fn test_parse_auxv_3() {
        let entries = [(3, 0x0804_8034), (9, 0x0804_af80), (25, 0xffff_c90b)];
        let buf = make_auxv(&entries, 4);
        let m = parse_auxv(&buf, true).unwrap();
        assert_eq!(m.get(&3), Some(&0x0804_8034));
        assert_eq!(m.get(&9), Some(&0x0804_af80));
        assert_eq!(m.get(&25), Some(&0xffff_c90b));
        assert_eq!(m.len(), 3);
    }

    #[test]
    fn test_parse_auxv_4() {
        let entries = [(3, 0x0804_8034), (9, 0x0804_af80), (25, 0xffff_c90b)];
        let buf = make_auxv(&entries, 4);
        let wrong = parse_auxv(&buf, false);
        let recovered = matches!(&wrong, Ok(m) if m.get(&9) == Some(&0x0804_af80));
        assert!(!recovered, "{wrong:?}");
    }

    #[cfg(feature = "oci")]
    #[test]
    fn test_proc_oom_score_adj() {
        let data = std::fs::read_to_string("/proc/self/oom_score_adj").unwrap();
        let score = data.trim().parse::<i32>().unwrap();
        proc_oom_score_adj(score).unwrap();
    }

    #[test]
    fn test_proc_char_dev_1() {
        assert!(proc_char_dev(proc_open(None).unwrap()).is_ok());
    }

    #[test]
    fn test_proc_char_dev_2() {
        assert!(!proc_char_dev(proc_open(None).unwrap()).unwrap().is_empty());
    }

    #[test]
    fn test_proc_char_dev_3() {
        assert!(proc_char_dev(proc_open(None).unwrap())
            .unwrap()
            .iter()
            .any(|dev| dev.name.as_bytes() == b"tty"));
    }

    #[test]
    fn test_proc_char_dev_major_1() {
        assert_eq!(proc_char_dev_major(b"tty"), Some(4));
        assert_eq!(proc_char_dev_major(b"syd-no-such-driver"), None);
    }

    #[test]
    fn test_proc_kernel_randomize_va_space() {
        matches!(
            proc_kernel_randomize_va_space(proc_open(None).unwrap()),
            Ok(0 | 1 | 2)
        );
    }
}