nixvm 0.0.0

A portable VM-style sandbox that runs a real Linux userland by emulating Linux syscalls directly (no guest kernel, no device emulation).
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
//! Synthesized `/proc` filesystem.
//!
//! Presents the set of pseudo-files a Linux userland pokes at during startup
//! and everyday operation. There are two flavours of content:
//!
//! * **Static** files — `version`, `filesystems`, `mounts`, … — carry fixed,
//!   plausible bytes baked in at compile time. A few system files
//!   (`cpuinfo`, `stat`) are *rendered* rather than static, so their per-CPU
//!   blocks track the injected core count.
//! * **Per-process** files under `self/` — `cmdline`, `status`, `maps`, the
//!   `exe`/`cwd` symlinks, `fd/`, … — are rendered from a [`ProcData`] value.
//!   The backend ships sensible placeholders; the kernel injects the real
//!   running-process data later through [`ProcFs::set_self`], keeping this
//!   file free of any dependency on the process model.
//!
//! `/proc/<pid>` (for the injected pid) is a transparent alias of `/proc/self`
//! — every path under it is rewritten to its `self/...` equivalent before any
//! lookup — so the two trees always agree without doubling the storage.
//!
//! Layout is a small fixed tree (`""`, `self`, `sys`, `sys/kernel`); paths are
//! matched directly rather than through a stored map. `self/fd/<n>` entries
//! are the one dynamic exception, sized by however many descriptors the
//! kernel injected. The backend is read-only, so every mutating method keeps
//! the trait's `EROFS` default.

use std::fmt::Write as _;
use std::io;

use super::{Attrs, DirEntry, MountFs, NodeKind};

/// Unix mode type bit for a directory.
const S_IFDIR: u32 = 0o040_000;
/// Unix mode type bit for a regular file.
const S_IFREG: u32 = 0o100_000;
/// Unix mode type bit for a symbolic link.
const S_IFLNK: u32 = 0o120_000;

/// `self/root`'s symlink target. A sandboxed process is never chrooted in
/// this backend, so it always resolves to the filesystem root.
const ROOT_TARGET: &str = "/";

/// Every static path this backend knows, in a fixed order. The 1-based index
/// into this table is the node's inode, which keeps every inode distinct for
/// free. `self/fd/<n>` entries are not listed here — see [`fd_inode`].
const PATHS: &[&str] = &[
    "", // root directory — inode 1
    "self",
    "sys",
    "sys/kernel",
    "cpuinfo",
    "meminfo",
    "version",
    "uptime",
    "loadavg",
    "stat",
    "filesystems",
    "mounts",
    "cmdline",
    "sys/kernel/ostype",
    "sys/kernel/osrelease",
    "sys/kernel/hostname",
    "sys/kernel/pid_max",
    "self/cmdline",
    "self/status",
    "self/stat",
    "self/comm",
    "self/maps",
    "self/exe",
    "self/cwd",
    "self/auxv",
    "self/fd",
    "net",
    "net/tcp",
    "net/tcp6",
    "net/udp",
    "net/udp6",
    "net/unix",
    "net/dev",
    "net/route",
    "net/snmp",
    "net/protocols",
    "sys/net",
    "sys/net/core",
    "sys/net/core/somaxconn",
    "sys/net/ipv4",
    "sys/net/ipv4/tcp_rmem",
    "sys/net/ipv4/tcp_wmem",
    "sys/net/ipv4/ip_local_port_range",
    "sys/vm",
    "sys/vm/overcommit_memory",
    "sys/vm/max_map_count",
    "sys/fs",
    "sys/fs/file-max",
    "sys/fs/nr_open",
    "diskstats",
    "partitions",
    "swaps",
    "modules",
    "devices",
    "self/mountinfo",
    "self/mounts",
    "self/smaps",
    "self/statm",
    "self/limits",
    "self/io",
    "self/oom_score",
    "self/oom_score_adj",
    "self/wchan",
    "self/environ",
    "self/root",
    "self/sched",
    "self/schedstat",
    "self/personality",
    "self/setgroups",
    "self/gid_map",
    "self/uid_map",
    "sys/kernel/random",
    "sys/kernel/random/boot_id",
    "sys/kernel/random/uuid",
    "sys/kernel/random/entropy_avail",
    "sys/kernel/random/poolsize",
    "sys/kernel/version",
    "sys/kernel/threads-max",
    "sys/kernel/ngroups_max",
    "sys/kernel/cap_last_cap",
    "sys/kernel/sched_rr_timeslice_ms",
    "kallsyms",
    "keys",
    "key-users",
    "locks",
    "vmstat",
    "zoneinfo",
    "buddyinfo",
    "consoles",
];

/// Static top-level file names, in `readdir("")` order.
const ROOT_FILES: &[&str] = &[
    "cpuinfo",
    "meminfo",
    "version",
    "uptime",
    "loadavg",
    "stat",
    "filesystems",
    "mounts",
    "cmdline",
    "diskstats",
    "partitions",
    "swaps",
    "modules",
    "devices",
    "kallsyms",
    "keys",
    "key-users",
    "locks",
    "vmstat",
    "zoneinfo",
    "buddyinfo",
    "consoles",
];

/// Per-process entry names under `self/`, in `readdir("self")` order. `exe`
/// and `cwd` are symlinks, `fd` is a directory, the rest are files.
const SELF_FILES: &[&str] = &[
    "cmdline",
    "status",
    "stat",
    "comm",
    "maps",
    "exe",
    "cwd",
    "auxv",
    "fd",
    "mountinfo",
    "mounts",
    "smaps",
    "statm",
    "limits",
    "io",
    "oom_score",
    "oom_score_adj",
    "wchan",
    "environ",
    "root",
    "sched",
    "schedstat",
    "personality",
    "setgroups",
    "gid_map",
    "uid_map",
];

/// Tunables exposed under `sys/kernel/`, excluding the `random/` subdirectory
/// (which [`ProcFs::readdir`] appends separately since it's a directory, not
/// a file).
const SYS_KERNEL_FILES: &[&str] = &[
    "ostype",
    "osrelease",
    "hostname",
    "pid_max",
    "version",
    "threads-max",
    "ngroups_max",
    "cap_last_cap",
    "sched_rr_timeslice_ms",
];

/// File names under `sys/kernel/random/`, in `readdir("sys/kernel/random")`
/// order.
const SYS_KERNEL_RANDOM_FILES: &[&str] = &["boot_id", "uuid", "entropy_avail", "poolsize"];

/// File names under `net/`, in `readdir("net")` order.
const NET_FILES: &[&str] = &[
    "tcp",
    "tcp6",
    "udp",
    "udp6",
    "unix",
    "dev",
    "route",
    "snmp",
    "protocols",
];

/// Tunables exposed under `sys/net/core/`.
const SYS_NET_CORE_FILES: &[&str] = &["somaxconn"];

/// Tunables exposed under `sys/net/ipv4/`.
const SYS_NET_IPV4_FILES: &[&str] = &["tcp_rmem", "tcp_wmem", "ip_local_port_range"];

/// Tunables exposed under `sys/vm/`.
const SYS_VM_FILES: &[&str] = &["overcommit_memory", "max_map_count"];

/// Tunables exposed under `sys/fs/`.
const SYS_FS_FILES: &[&str] = &["file-max", "nr_open"];

// ---- static file bodies (each ends with a newline) ----

const MEMINFO: &str = "MemTotal:        2048000 kB\n\
MemFree:         1024000 kB\n\
MemAvailable:    1536000 kB\n\
Buffers:               0 kB\n\
Cached:           512000 kB\n\
SwapTotal:             0 kB\n\
SwapFree:              0 kB\n";

const VERSION: &str = "Linux version 6.1.0-nixvm (nixvm@nixvm) (gcc) #1 SMP nixvm\n";

const UPTIME: &str = "0.00 0.00\n";

const LOADAVG: &str = "0.00 0.00 0.00 1/1 1\n";

const FILESYSTEMS: &str = "nodev\ttmpfs\n\
nodev\tproc\n\
nodev\tsysfs\n\
nodev\tdevtmpfs\n";

const MOUNTS: &str = "tmpfs / tmpfs rw 0 0\n\
proc /proc proc rw 0 0\n\
sysfs /sys sysfs rw 0 0\n\
devtmpfs /dev devtmpfs rw 0 0\n";

/// `self/mountinfo`'s body, in the `36 35 98:0 /mnt1 /mnt2 rw,noatime … - fstype source opts`
/// format documented in `proc(5)`.
const MOUNTINFO: &str = "1 0 0:1 / / rw,relatime shared:1 - tmpfs tmpfs rw\n\
2 1 0:2 / /proc rw,nosuid,nodev,noexec,relatime shared:2 - proc proc rw\n\
3 1 0:3 / /sys rw,nosuid,nodev,noexec,relatime shared:3 - sysfs sysfs rw\n\
4 1 0:4 / /dev rw,nosuid,relatime shared:4 - devtmpfs devtmpfs rw\n";

const CMDLINE: &str = "\n";

const OSTYPE: &str = "Linux\n";
const OSRELEASE: &str = "6.1.0-nixvm\n";
const HOSTNAME: &str = "nixvm\n";
const PID_MAX: &str = "32768\n";
/// `sys/kernel/version`'s body — distinct from top-level `version`
/// ([`VERSION`]): this one is just the build tag, as `proc(5)` documents.
const KERNEL_VERSION: &str = "#1 SMP nixvm\n";
const THREADS_MAX: &str = "127871\n";
const NGROUPS_MAX: &str = "65536\n";
/// Last valid capability index (`CAP_CHECKPOINT_RESTORE` on a modern kernel).
const CAP_LAST_CAP: &str = "40\n";
const SCHED_RR_TIMESLICE_MS: &str = "100\n";

// ---- sys/kernel/random/* ----

/// Fixed-but-valid UUIDs: a synthetic sandbox has no real boot entropy, but
/// userland only ever checks the shape, not the value.
const BOOT_ID: &str = "2f38a1c4-9b3e-4d3a-8f2b-6b6f2a9c1e10\n";
const RANDOM_UUID: &str = "b6d1a0f4-7c3d-4a2e-9f1b-3c5d7e9a2b41\n";
const ENTROPY_AVAIL: &str = "256\n";
const POOLSIZE: &str = "4096\n";

// ---- /proc/net/* ----

const NET_TCP_HEADER: &str = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n";

const NET_TCP6_HEADER: &str = "  sl  \
local_address                         remote_address                        st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n";

const NET_UDP_HEADER: &str = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when \
retrnsmt   uid  timeout inode ref pointer drops\n";

const NET_UDP6_HEADER: &str = "  sl  \
local_address                         remote_address                        st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode ref pointer drops\n";

const NET_UNIX: &str = "Num       RefCount Protocol Flags    Type St Inode Path\n";

const NET_DEV: &str = "Inter-|   Receive                                                |  Transmit\n\
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed\n\
    lo:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0\n";

const NET_ROUTE: &str =
    "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n";

const NET_SNMP: &str = "Ip: Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates\n\
Ip: 1 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n\
Icmp: InMsgs InErrors InCsumErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps\n\
Icmp: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n\
Tcp: RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts InCsumErrors\n\
Tcp: 1 200 120000 -1 0 0 0 0 0 0 0 0 0 0 0\n\
Udp: InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors InCsumErrors IgnoredMulti\n\
Udp: 0 0 0 0 0 0 0 0\n";

const NET_PROTOCOLS: &str = "protocol  size sockets  memory press maxhdr  slab module     cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n\
TCP        2144   0       -1     no     20     yes   kernel     y  y  y  y  y  y  y  y  y  y  y  y  n  n  y  y  y  n\n\
UDP        1408   0       -1     no      0     yes   kernel     y  y  y  n  n  n  y  y  y  y  y  n  n  n  y  y  y  n\n";

// ---- /proc/sys/{net,vm,fs}/* ----

const SOMAXCONN: &str = "4096\n";
const TCP_RMEM: &str = "4096\t131072\t6291456\n";
const TCP_WMEM: &str = "4096\t16384\t4194304\n";
const IP_LOCAL_PORT_RANGE: &str = "32768\t60999\n";
const OVERCOMMIT_MEMORY: &str = "0\n";
const MAX_MAP_COUNT: &str = "65530\n";
const FILE_MAX: &str = "1048576\n";
const NR_OPEN: &str = "1048576\n";

// ---- misc top-level files ----

const DISKSTATS: &str = "   8       0 vda 0 0 0 0 0 0 0 0 0 0 0\n";
const PARTITIONS: &str = "major minor  #blocks  name\n\n   8        0     102400 vda\n";
const SWAPS: &str = "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n";
/// No modules are ever loaded in a synthetic kernel; an empty file is the
/// valid, real-world rendering of that state.
const MODULES: &str = "";
const DEVICES: &str = "Character devices:\n\
  1 mem\n\
  4 tty\n\
  5 /dev/tty\n\
  5 /dev/console\n\
 10 misc\n\
136 pts\n\
\n\
Block devices:\n\
  8 sd\n\
  9 md\n\
259 blkext\n";

/// No kernel modules ever register symbols in a synthetic kernel; a couple of
/// placeholder entries are a valid, minimal rendering (a fully empty file
/// would be valid too, but this exercises callers that expect at least one
/// parseable line).
const KALLSYMS: &str = "0000000000000000 t placeholder\n\
0000000000000000 t placeholder2\n";
/// No keys are ever created in a synthetic kernel; empty is the valid,
/// real-world rendering of that state.
const KEYS: &str = "";
const KEY_USERS: &str = "";
/// No file locks are ever held in a synthetic kernel; empty is valid.
const LOCKS: &str = "";

const VMSTAT: &str = "nr_free_pages 262144\n\
nr_zone_inactive_anon 0\n\
nr_zone_active_anon 0\n\
nr_zone_inactive_file 0\n\
nr_zone_active_file 0\n\
nr_zone_unevictable 0\n\
nr_slab_reclaimable 1024\n\
nr_slab_unreclaimable 2048\n\
pgfault 0\n\
pgmajfault 0\n";

const ZONEINFO: &str = "Node 0, zone   Normal\n\
  pages free     262144\n\
        min      1024\n\
        low      1280\n\
        high     1536\n\
        spanned  524288\n\
        present  524288\n\
        managed  512000\n";

const BUDDYINFO: &str =
    "Node 0, zone   Normal    100    50    25    12     6     3     1     0     0     0     0\n";

const CONSOLES: &str = "ttyS0                -W- (EC p a)    4:64\n";

// ---- self/* static bodies (independent of injected ProcData) ----

const LIMITS: &str = "Limit                     Soft Limit           Hard Limit           Units     \n\
Max cpu time              unlimited            unlimited            seconds   \n\
Max file size             unlimited            unlimited            bytes     \n\
Max data size             unlimited            unlimited            bytes     \n\
Max stack size            8388608              unlimited            bytes     \n\
Max core file size        0                    unlimited            bytes     \n\
Max resident set          unlimited            unlimited            bytes     \n\
Max processes             15746                15746                processes \n\
Max open files            1024                 4096                 files     \n\
Max locked memory         65536                65536                bytes     \n\
Max address space         unlimited            unlimited            bytes     \n\
Max file locks            unlimited            unlimited            locks     \n\
Max pending signals       15746                15746                signals   \n\
Max msgqueue size         819200               819200               bytes     \n\
Max nice priority         0                    0                              \n\
Max realtime priority     0                    0                              \n\
Max realtime timeout      unlimited            unlimited            us        \n";

const IO: &str = "rchar: 0\n\
wchar: 0\n\
syscr: 0\n\
syscw: 0\n\
read_bytes: 0\n\
write_bytes: 0\n\
cancelled_write_bytes: 0\n";

const OOM_SCORE: &str = "0\n";
const OOM_SCORE_ADJ: &str = "0\n";
/// `self/wchan` has no trailing newline on a real kernel — it's a single
/// symbol name (or `0` when idle), not a line-oriented text file.
const WCHAN: &str = "0";

/// `self/environ`'s body: NUL-separated `KEY=value` pairs, as the kernel
/// presents them (including the trailing NUL after the last entry).
/// [`ProcData`] carries no environment yet, so this is a minimal-but-plausible
/// static default rather than an injected value.
const ENVIRON: &str =
    "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\0HOME=/root\0TERM=xterm\0";
/// `self/schedstat`'s three whitespace-separated fields: time spent on the
/// CPU, time spent waiting to run, and timeslices run — all `0` since a
/// synthetic process hasn't actually been scheduled.
const SCHEDSTAT: &str = "0 0 0\n";
/// `self/personality`'s body: `PER_LINUX`, the standard Linux personality.
const PERSONALITY: &str = "0\n";
/// `self/setgroups`'s body: `allow`, the default before a user namespace
/// restricts `setgroups(2)`.
const SETGROUPS: &str = "allow\n";
/// Shared body for `self/uid_map` and `self/gid_map`: a single line mapping
/// the whole id range to itself (`id-inside-ns id-outside-ns length`).
const UID_GID_MAP: &str = "0 0 4294967295\n";

/// Running-process (and lightweight system) data backing the `self/` files
/// plus the CPU-count-sensitive system files.
///
/// The kernel builds one of these from the real process it is executing and
/// installs it with [`ProcFs::set_self`]; until then [`ProcData::default`]
/// supplies placeholders so every file still renders something plausible.
#[derive(Debug, Clone)]
pub struct ProcData {
    /// Raw `argv` for `self/cmdline`, NUL-separated as the kernel presents it.
    pub cmdline: Vec<u8>,
    /// Absolute path the `self/exe` symlink resolves to.
    pub exe: String,
    /// Absolute path the `self/cwd` symlink resolves to.
    pub cwd: String,
    /// Body of `self/maps`. Empty means "not injected"; a minimal plausible
    /// map (image + heap + stack) is synthesized instead.
    pub maps: String,
    /// Short command name for `self/comm` (and the parenthesised field of
    /// `self/stat`).
    pub comm: String,
    /// The zeroth argument the process was launched with.
    pub argv0: String,
    /// Process id. Also the `<pid>` directory that mirrors `self/`. `0` means
    /// no numeric alias is published.
    pub pid: u32,
    /// Parent process id.
    pub ppid: u32,
    /// Real/effective/saved/filesystem uid (all reported equal, as a static
    /// sandbox has no reason to differ).
    pub uid: u32,
    /// Real/effective/saved/filesystem gid.
    pub gid: u32,
    /// Single-letter run state (`R`, `S`, `D`, `Z`, `T`) for `stat`/`status`.
    pub state: char,
    /// Thread count.
    pub threads: u32,
    /// Resident + virtual memory footprint, in kB, for `status`/`stat`.
    pub vm_size_kb: u64,
    pub vm_rss_kb: u64,
    /// Open file descriptors: `(fd number, symlink target)`, backing
    /// `self/fd/`. Empty means nothing is published there.
    pub fds: Vec<(u32, String)>,
    /// CPU core count backing the per-cpu blocks of `cpuinfo` and `stat`.
    pub nproc: usize,
    /// Raw `self/auxv` bytes (pairs of `(type, value)` `u64`s on a real
    /// kernel); empty is a valid, minimal rendering.
    pub auxv: Vec<u8>,
}

impl Default for ProcData {
    fn default() -> Self {
        Self {
            cmdline: Vec::new(),
            exe: "/bin/busybox".to_string(),
            cwd: "/".to_string(),
            maps: String::new(),
            comm: "nixvm".to_string(),
            argv0: "busybox".to_string(),
            pid: 1,
            ppid: 0,
            uid: 0,
            gid: 0,
            state: 'R',
            threads: 1,
            vm_size_kb: 4096,
            vm_rss_kb: 1024,
            fds: Vec::new(),
            nproc: 1,
            auxv: Vec::new(),
        }
    }
}

/// The synthesized `/proc` backend.
#[derive(Debug)]
pub struct ProcFs {
    data: ProcData,
}

impl Default for ProcFs {
    fn default() -> Self {
        Self::new()
    }
}

impl ProcFs {
    #[must_use]
    pub fn new() -> Self {
        Self {
            data: ProcData::default(),
        }
    }

    /// Install the running-process data backing the `self/` files (and the
    /// `<pid>` alias, and the per-cpu system files).
    pub fn set_self(&mut self, data: ProcData) {
        self.data = data;
    }

    /// Rewrite a numeric-pid path to its `self/...` equivalent when it names
    /// the injected pid, leaving every other path untouched. This is the only
    /// place `<pid>` paths are special-cased; everything downstream only ever
    /// sees `self`-rooted or static paths.
    fn normalize(&self, rel: &str) -> String {
        if self.data.pid != 0 {
            let pid_s = self.data.pid.to_string();
            if rel == pid_s {
                return "self".to_string();
            }
            if let Some(rest) = rel
                .strip_prefix(pid_s.as_str())
                .and_then(|r| r.strip_prefix('/'))
            {
                return format!("self/{rest}");
            }
        }
        rel.to_string()
    }

    /// The rendered bytes of a readable file, or `None` if `rel` is not a
    /// regular file (a directory, a symlink, or unknown).
    fn content(&self, rel: &str) -> Option<Vec<u8>> {
        match rel {
            "cpuinfo" => return Some(cpuinfo_body(self.data.nproc).into_bytes()),
            "stat" => return Some(stat_body(self.data.nproc).into_bytes()),
            _ => {}
        }
        if let Some(bytes) = static_content(rel) {
            return Some(bytes.to_vec());
        }
        self.self_content(rel)
    }

    /// Render a per-process file. `self/exe`, `self/cwd` and `self/fd/<n>`
    /// are deliberately excluded — they are symlinks, not readable files.
    fn self_content(&self, rel: &str) -> Option<Vec<u8>> {
        let d = &self.data;
        let body = match rel {
            "self/cmdline" => return Some(d.cmdline.clone()),
            "self/maps" => {
                let text = if d.maps.is_empty() {
                    default_maps(&d.exe)
                } else {
                    d.maps.clone()
                };
                return Some(text.into_bytes());
            }
            "self/auxv" => return Some(d.auxv.clone()),
            "self/comm" => format!("{}\n", d.comm),
            "self/stat" => self_stat_body(d),
            "self/statm" => statm_body(d),
            "self/sched" => sched_body(d),
            "self/smaps" => {
                let text = if d.maps.is_empty() {
                    default_maps(&d.exe)
                } else {
                    d.maps.clone()
                };
                smaps_body(&text)
            }
            "self/status" => format!(
                "Name:\t{comm}\n\
                 State:\t{state} ({state_desc})\n\
                 Tgid:\t{pid}\n\
                 Pid:\t{pid}\n\
                 PPid:\t{ppid}\n\
                 Uid:\t{uid}\t{uid}\t{uid}\t{uid}\n\
                 Gid:\t{gid}\t{gid}\t{gid}\t{gid}\n\
                 Threads:\t{threads}\n\
                 VmSize:\t{vsize} kB\n\
                 VmRSS:\t{rss} kB\n",
                comm = d.comm,
                state = d.state,
                state_desc = state_desc(d.state),
                pid = d.pid,
                ppid = d.ppid,
                uid = d.uid,
                gid = d.gid,
                threads = d.threads,
                vsize = d.vm_size_kb,
                rss = d.vm_rss_kb,
            ),
            _ => return None,
        };
        Some(body.into_bytes())
    }

    /// `self/fd/<n>`'s symlink target, if that descriptor is published.
    fn fd_target(&self, n: u32) -> Option<&str> {
        self.data
            .fds
            .iter()
            .find(|(fd, _)| *fd == n)
            .map(|(_, target)| target.as_str())
    }
}

/// Byte body of a static file, or `None` if `rel` is not one.
fn static_content(rel: &str) -> Option<&'static [u8]> {
    let text = match rel {
        "meminfo" => MEMINFO,
        "version" => VERSION,
        "uptime" => UPTIME,
        "loadavg" => LOADAVG,
        "filesystems" => FILESYSTEMS,
        "mounts" | "self/mounts" => MOUNTS,
        "cmdline" => CMDLINE,
        "sys/kernel/ostype" => OSTYPE,
        "sys/kernel/osrelease" => OSRELEASE,
        "sys/kernel/hostname" => HOSTNAME,
        "sys/kernel/pid_max" => PID_MAX,
        "sys/kernel/version" => KERNEL_VERSION,
        "sys/kernel/threads-max" => THREADS_MAX,
        "sys/kernel/ngroups_max" => NGROUPS_MAX,
        "sys/kernel/cap_last_cap" => CAP_LAST_CAP,
        "sys/kernel/sched_rr_timeslice_ms" => SCHED_RR_TIMESLICE_MS,
        "sys/kernel/random/boot_id" => BOOT_ID,
        "sys/kernel/random/uuid" => RANDOM_UUID,
        "sys/kernel/random/entropy_avail" => ENTROPY_AVAIL,
        "sys/kernel/random/poolsize" => POOLSIZE,
        "net/tcp" => NET_TCP_HEADER,
        "net/tcp6" => NET_TCP6_HEADER,
        "net/udp" => NET_UDP_HEADER,
        "net/udp6" => NET_UDP6_HEADER,
        "net/unix" => NET_UNIX,
        "net/dev" => NET_DEV,
        "net/route" => NET_ROUTE,
        "net/snmp" => NET_SNMP,
        "net/protocols" => NET_PROTOCOLS,
        "sys/net/core/somaxconn" => SOMAXCONN,
        "sys/net/ipv4/tcp_rmem" => TCP_RMEM,
        "sys/net/ipv4/tcp_wmem" => TCP_WMEM,
        "sys/net/ipv4/ip_local_port_range" => IP_LOCAL_PORT_RANGE,
        "sys/vm/overcommit_memory" => OVERCOMMIT_MEMORY,
        "sys/vm/max_map_count" => MAX_MAP_COUNT,
        "sys/fs/file-max" => FILE_MAX,
        "sys/fs/nr_open" => NR_OPEN,
        "diskstats" => DISKSTATS,
        "partitions" => PARTITIONS,
        "swaps" => SWAPS,
        "modules" => MODULES,
        "devices" => DEVICES,
        "kallsyms" => KALLSYMS,
        "keys" => KEYS,
        "key-users" => KEY_USERS,
        "locks" => LOCKS,
        "vmstat" => VMSTAT,
        "zoneinfo" => ZONEINFO,
        "buddyinfo" => BUDDYINFO,
        "consoles" => CONSOLES,
        "self/mountinfo" => MOUNTINFO,
        "self/limits" => LIMITS,
        "self/io" => IO,
        "self/oom_score" => OOM_SCORE,
        "self/oom_score_adj" => OOM_SCORE_ADJ,
        "self/wchan" => WCHAN,
        "self/environ" => ENVIRON,
        "self/schedstat" => SCHEDSTAT,
        "self/personality" => PERSONALITY,
        "self/setgroups" => SETGROUPS,
        "self/gid_map" | "self/uid_map" => UID_GID_MAP,
        _ => return None,
    };
    Some(text.as_bytes())
}

/// Render `cpuinfo`, one block per core, matching the injected `nproc`
/// (never fewer than one core).
fn cpuinfo_body(nproc: usize) -> String {
    let mut out = String::new();
    for i in 0..nproc.max(1) {
        write_cpuinfo_block(&mut out, i);
    }
    out
}

/// Append one core's block to `cpuinfo`. The fields track the build's own
/// target architecture — the ISA nixvm's interpreter actually executes on —
/// falling back to the aarch64 shape (matching this backend's long-standing
/// default) on anything else.
fn write_cpuinfo_block(out: &mut String, i: usize) {
    if cfg!(target_arch = "x86_64") {
        let _ = write!(
            out,
            "processor\t: {i}\n\
             vendor_id\t: GenuineIntel\n\
             cpu family\t: 6\n\
             model name\t: nixvm Virtual CPU\n\
             flags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov \
             pat pse36 clflush mmx fxsr sse sse2 ht syscall nx lm constant_tsc \
             rep_good nopl cpuid pni pclmulqdq ssse3 cx16 sse4_1 sse4_2 x2apic \
             popcnt aes xsave avx rdrand hypervisor lahf_lm abm 3dnowprefetch\n\
             bogomips\t: 100.00\n\n"
        );
    } else {
        let _ = write!(
            out,
            "processor\t: {i}\n\
             BogoMIPS\t: 100.00\n\
             Features\t: fp asimd aes pmull sha1 sha2 crc32 atomics fphp asimdhp \
             cpuid asimdrdm lrcpc dcpop asimddp\n\
             CPU implementer\t: 0x41\n\
             CPU architecture: 8\n\
             CPU variant\t: 0x0\n\
             CPU part\t: 0xd08\n\
             CPU revision\t: 0\n\n"
        );
    }
}

/// Render `/proc/stat`, with one `cpuN` line per injected core.
fn stat_body(nproc: usize) -> String {
    let mut out = String::from("cpu  0 0 0 0 0 0 0 0 0 0\n");
    for i in 0..nproc.max(1) {
        let _ = writeln!(out, "cpu{i} 0 0 0 0 0 0 0 0 0 0");
    }
    out.push_str(
        "intr 0\n\
         ctxt 0\n\
         btime 0\n\
         processes 1\n\
         procs_running 1\n\
         procs_blocked 0\n",
    );
    out
}

/// A minimal but plausible `self/maps` body used when the kernel hasn't
/// injected real mapping data: a text/data image mapping for `exe`, plus a
/// heap and a stack region — the ranges a userland typically checks for.
fn default_maps(exe: &str) -> String {
    format!(
        "00400000-00401000 r-xp 00000000 00:00 0                          {exe}\n\
         00600000-00601000 rw-p 00000000 00:00 0                          {exe}\n\
         01000000-01021000 rw-p 00000000 00:00 0                          [heap]\n\
         7ffffffde000-7ffffffff000 rw-p 00000000 00:00 0                  [stack]\n"
    )
}

/// Human description of a single-letter run state, for `status`'s `State:`
/// line.
fn state_desc(state: char) -> &'static str {
    match state {
        'R' => "running",
        'S' => "sleeping",
        'D' => "disk sleep",
        'Z' => "zombie",
        'T' => "stopped",
        _ => "unknown",
    }
}

/// Push `val` onto `f` `n` times; used to fill the many always-zero `stat`
/// fields without a wall of repeated literals.
fn push_n(f: &mut Vec<String>, val: &str, n: usize) {
    for _ in 0..n {
        f.push(val.to_string());
    }
}

/// Render `self/stat`'s full 52-field line (see proc(5)), with the fields
/// nixvm actually tracks filled in and the rest zeroed.
fn self_stat_body(d: &ProcData) -> String {
    let pid = d.pid.to_string();
    let vsize = d.vm_size_kb * 1024;
    let rss = d.vm_rss_kb / 4; // rss is reported in pages, not kB
    let mut f: Vec<String> = Vec::with_capacity(52);
    f.push(pid.clone()); // 1 pid
    f.push(format!("({})", d.comm)); // 2 comm
    f.push(d.state.to_string()); // 3 state
    f.push(d.ppid.to_string()); // 4 ppid
    f.push(pid.clone()); // 5 pgrp
    f.push(pid); // 6 session
    f.push("0".to_string()); // 7 tty_nr
    f.push("-1".to_string()); // 8 tpgid
    f.push("0".to_string()); // 9 flags
    push_n(&mut f, "0", 4); // 10-13 minflt cminflt majflt cmajflt
    push_n(&mut f, "0", 4); // 14-17 utime stime cutime cstime
    f.push("20".to_string()); // 18 priority
    f.push("0".to_string()); // 19 nice
    f.push(d.threads.to_string()); // 20 num_threads
    f.push("0".to_string()); // 21 itrealvalue
    f.push("0".to_string()); // 22 starttime
    f.push(vsize.to_string()); // 23 vsize
    f.push(rss.to_string()); // 24 rss
    f.push("18446744073709551615".to_string()); // 25 rsslim
    push_n(&mut f, "0", 5); // 26-30 startcode endcode startstack kstkesp kstkeip
    push_n(&mut f, "0", 4); // 31-34 signal blocked sigignore sigcatch
    f.push("0".to_string()); // 35 wchan
    f.push("0".to_string()); // 36 nswap
    f.push("0".to_string()); // 37 cnswap
    f.push("17".to_string()); // 38 exit_signal
    f.push("0".to_string()); // 39 processor
    push_n(&mut f, "0", 2); // 40-41 rt_priority policy
    f.push("0".to_string()); // 42 delayacct_blkio_ticks
    push_n(&mut f, "0", 2); // 43-44 guest_time cguest_time
    push_n(&mut f, "0", 2); // 45-46 start_data end_data
    f.push("0".to_string()); // 47 start_brk
    push_n(&mut f, "0", 4); // 48-51 arg_start arg_end env_start env_end
    f.push("0".to_string()); // 52 exit_code
    debug_assert_eq!(f.len(), 52);
    format!("{}\n", f.join(" "))
}

/// Render `self/statm`'s 7 whitespace-separated page counts (see `proc(5)`):
/// `size resident shared text lib data dt`. Sizes are derived from the
/// injected kB figures assuming 4 kB pages.
fn statm_body(d: &ProcData) -> String {
    const PAGE_KB: u64 = 4;
    let size = (d.vm_size_kb / PAGE_KB).max(1);
    let resident = (d.vm_rss_kb / PAGE_KB).max(1);
    let shared = 0u64;
    let text = 1u64.min(size);
    let lib = 0u64;
    let data = size.saturating_sub(text);
    let dt = 0u64;
    format!("{size} {resident} {shared} {text} {lib} {data} {dt}\n")
}

/// Render `self/sched`'s human-readable scheduling-statistics dump (see
/// `sched_show_task()` in the kernel): a header line naming the process,
/// followed by the handful of `se.*`/`nr_*` fields userland tools actually
/// scrape, all zeroed since a synthetic process has no real scheduling
/// history.
fn sched_body(d: &ProcData) -> String {
    format!(
        "{comm} ({pid}, #threads: {threads})\n\
         ------------------------------------------------------------------\n\
         se.exec_start                               :               0.000000\n\
         se.vruntime                                 :               0.000000\n\
         se.sum_exec_runtime                         :               0.000000\n\
         nr_switches                                 :                      0\n\
         nr_voluntary_switches                       :                      0\n\
         nr_involuntary_switches                     :                      0\n\
         se.load.weight                              :                   1024\n\
         policy                                      :                      0\n\
         prio                                        :                    120\n",
        comm = d.comm,
        pid = d.pid,
        threads = d.threads,
    )
}

/// The `VmFlags` shorthand for a `self/maps` permission token (e.g. `r-xp`),
/// approximating what the kernel reports for a mapping with those
/// permissions.
fn vmflags_for(perms: &str) -> String {
    let mut flags = Vec::new();
    if perms.contains('r') {
        flags.push("rd");
    }
    if perms.contains('w') {
        flags.push("wr");
    }
    if perms.contains('x') {
        flags.push("ex");
    }
    flags.push("mr");
    flags.push("mw");
    flags.push("me");
    if perms.contains('w') {
        flags.push("dw");
    }
    flags.join(" ")
}

/// Render `self/smaps`: every line of `maps` (see [`default_maps`]) followed
/// by its per-mapping statistics block, sized from the line's own address
/// range.
fn smaps_body(maps: &str) -> String {
    let mut out = String::new();
    for line in maps.lines() {
        if line.is_empty() {
            continue;
        }
        let _ = writeln!(out, "{line}");
        let mut fields = line.split_whitespace();
        let range = fields.next().unwrap_or("");
        let perms = fields.next().unwrap_or("----");
        let size_kb = range
            .split_once('-')
            .and_then(|(s, e)| {
                let s = u64::from_str_radix(s, 16).ok()?;
                let e = u64::from_str_radix(e, 16).ok()?;
                Some(e.saturating_sub(s) / 1024)
            })
            .unwrap_or(4)
            .max(4);
        let writable = perms.contains('w');
        let (private_clean, private_dirty) = if writable { (0, size_kb) } else { (size_kb, 0) };
        let zero = 0u64;
        let page_kb = 4u64;
        let flags = vmflags_for(perms);
        let _ = write!(
            out,
            "Size:           {size_kb:>10} kB\n\
             KernelPageSize: {page_kb:>10} kB\n\
             MMUPageSize:    {page_kb:>10} kB\n\
             Rss:            {size_kb:>10} kB\n\
             Pss:            {size_kb:>10} kB\n\
             Shared_Clean:   {zero:>10} kB\n\
             Shared_Dirty:   {zero:>10} kB\n\
             Private_Clean:  {private_clean:>10} kB\n\
             Private_Dirty:  {private_dirty:>10} kB\n\
             Referenced:     {size_kb:>10} kB\n\
             Anonymous:      {zero:>10} kB\n\
             AnonHugePages:  {zero:>10} kB\n\
             Swap:           {zero:>10} kB\n\
             SwapPss:        {zero:>10} kB\n\
             Locked:         {zero:>10} kB\n\
             VmFlags: {flags}\n"
        );
    }
    out
}

/// The inode for a known static path (its 1-based position in [`PATHS`]).
fn inode_of(rel: &str) -> Option<u64> {
    PATHS.iter().position(|p| *p == rel).map(|i| i as u64 + 1)
}

/// Deterministic inode for a `self/fd/<n>` symlink, kept clear of the
/// (small, fixed) range [`inode_of`] hands out.
fn fd_inode(fd: u32) -> u64 {
    100_000 + u64::from(fd)
}

/// Whether `rel` (already [`ProcFs::normalize`]d) names one of the fixed
/// directories.
fn is_dir(rel: &str) -> bool {
    matches!(
        rel,
        "" | "self"
            | "self/fd"
            | "sys"
            | "sys/kernel"
            | "sys/kernel/random"
            | "net"
            | "sys/net"
            | "sys/net/core"
            | "sys/net/ipv4"
            | "sys/vm"
            | "sys/fs"
    )
}

/// Build a directory entry, looking the inode up from the full path.
fn entry(name: &str, path: &str, kind: NodeKind) -> DirEntry {
    DirEntry {
        name: name.to_string(),
        kind,
        inode: inode_of(path).unwrap_or(0),
    }
}

/// Build directory entries for a flat list of file names under `prefix`
/// (e.g. `"net"` + `["tcp", ...]` -> `net/tcp`, …) — the common shape for
/// the many single-level tunable directories this backend exposes.
fn list_files(prefix: &str, names: &[&str]) -> Vec<DirEntry> {
    names
        .iter()
        .map(|n| {
            let path = format!("{prefix}/{n}");
            entry(n, &path, NodeKind::File)
        })
        .collect()
}

/// Copy `data[off..]` into `buf`, returning the byte count (0 at or past EOF).
fn read_slice(data: &[u8], off: u64, buf: &mut [u8]) -> usize {
    let off = off as usize;
    if off >= data.len() {
        return 0;
    }
    let n = buf.len().min(data.len() - off);
    buf[..n].copy_from_slice(&data[off..off + n]);
    n
}

fn enoent() -> io::Error {
    io::Error::from_raw_os_error(2) // ENOENT
}
fn eisdir() -> io::Error {
    io::Error::from_raw_os_error(21) // EISDIR
}
fn enotdir() -> io::Error {
    io::Error::from_raw_os_error(20) // ENOTDIR
}
fn einval() -> io::Error {
    io::Error::from_raw_os_error(22) // EINVAL
}

impl MountFs for ProcFs {
    fn stat(&mut self, rel: &str) -> Option<Attrs> {
        let rel = self.normalize(rel);
        let rel = rel.as_str();

        if let Some(n) = rel
            .strip_prefix("self/fd/")
            .and_then(|s| s.parse::<u32>().ok())
        {
            let target = self.fd_target(n)?;
            return Some(Attrs {
                kind: NodeKind::Symlink,
                size: target.len() as u64,
                mode: S_IFLNK | 0o777,
                uid: 0,
                gid: 0,
                mtime: 0,
                inode: fd_inode(n),
                nlink: 1,
                rdev: 0,
            });
        }

        let inode = inode_of(rel)?;
        let (kind, mode, size) = if is_dir(rel) {
            (NodeKind::Dir, S_IFDIR | 0o555, 0)
        } else if rel == "self/exe" {
            (
                NodeKind::Symlink,
                S_IFLNK | 0o777,
                self.data.exe.len() as u64,
            )
        } else if rel == "self/cwd" {
            (
                NodeKind::Symlink,
                S_IFLNK | 0o777,
                self.data.cwd.len() as u64,
            )
        } else if rel == "self/root" {
            (NodeKind::Symlink, S_IFLNK | 0o777, ROOT_TARGET.len() as u64)
        } else {
            let data = self.content(rel)?;
            (NodeKind::File, S_IFREG | 0o444, data.len() as u64)
        };
        Some(Attrs {
            kind,
            size,
            mode,
            uid: 0,
            gid: 0,
            mtime: 0,
            inode,
            nlink: 1,
            rdev: 0,
        })
    }

    fn read_at(&mut self, rel: &str, off: u64, buf: &mut [u8]) -> io::Result<usize> {
        let rel = self.normalize(rel);
        let rel = rel.as_str();
        if is_dir(rel) {
            return Err(eisdir());
        }
        if rel == "self/exe"
            || rel == "self/cwd"
            || rel == "self/root"
            || rel.starts_with("self/fd/")
        {
            return Err(einval()); // read on a symlink; use readlink
        }
        match self.content(rel) {
            Some(data) => Ok(read_slice(&data, off, buf)),
            None => Err(enoent()),
        }
    }

    fn readdir(&mut self, rel: &str) -> io::Result<Vec<DirEntry>> {
        let rel = self.normalize(rel);
        let rel = rel.as_str();
        match rel {
            "" => {
                let mut out: Vec<DirEntry> = ROOT_FILES
                    .iter()
                    .map(|n| entry(n, n, NodeKind::File))
                    .collect();
                out.push(entry("self", "self", NodeKind::Dir));
                if self.data.pid != 0 {
                    out.push(DirEntry {
                        name: self.data.pid.to_string(),
                        kind: NodeKind::Dir,
                        inode: inode_of("self").unwrap_or(0),
                    });
                }
                out.push(entry("sys", "sys", NodeKind::Dir));
                out.push(entry("net", "net", NodeKind::Dir));
                Ok(out)
            }
            "self" => Ok(SELF_FILES
                .iter()
                .map(|n| {
                    let path = format!("self/{n}");
                    let kind = match *n {
                        "exe" | "cwd" | "root" => NodeKind::Symlink,
                        "fd" => NodeKind::Dir,
                        _ => NodeKind::File,
                    };
                    entry(n, &path, kind)
                })
                .collect()),
            "self/fd" => Ok(self
                .data
                .fds
                .iter()
                .map(|(fd, _)| DirEntry {
                    name: fd.to_string(),
                    kind: NodeKind::Symlink,
                    inode: fd_inode(*fd),
                })
                .collect()),
            "sys" => Ok(vec![
                entry("kernel", "sys/kernel", NodeKind::Dir),
                entry("net", "sys/net", NodeKind::Dir),
                entry("vm", "sys/vm", NodeKind::Dir),
                entry("fs", "sys/fs", NodeKind::Dir),
            ]),
            "sys/kernel" => {
                let mut out = list_files("sys/kernel", SYS_KERNEL_FILES);
                out.push(entry("random", "sys/kernel/random", NodeKind::Dir));
                Ok(out)
            }
            "sys/kernel/random" => Ok(list_files("sys/kernel/random", SYS_KERNEL_RANDOM_FILES)),
            "net" => Ok(list_files("net", NET_FILES)),
            "sys/net" => Ok(vec![
                entry("core", "sys/net/core", NodeKind::Dir),
                entry("ipv4", "sys/net/ipv4", NodeKind::Dir),
            ]),
            "sys/net/core" => Ok(list_files("sys/net/core", SYS_NET_CORE_FILES)),
            "sys/net/ipv4" => Ok(list_files("sys/net/ipv4", SYS_NET_IPV4_FILES)),
            "sys/vm" => Ok(list_files("sys/vm", SYS_VM_FILES)),
            "sys/fs" => Ok(list_files("sys/fs", SYS_FS_FILES)),
            _ if rel.starts_with("self/fd/") => Err(enotdir()),
            _ if inode_of(rel).is_some() => Err(enotdir()),
            _ => Err(enoent()),
        }
    }

    fn readlink(&mut self, rel: &str) -> io::Result<String> {
        let rel = self.normalize(rel);
        let rel = rel.as_str();
        if rel == "self/exe" {
            return Ok(self.data.exe.clone());
        }
        if rel == "self/cwd" {
            return Ok(self.data.cwd.clone());
        }
        if rel == "self/root" {
            return Ok(ROOT_TARGET.to_string());
        }
        if let Some(n) = rel
            .strip_prefix("self/fd/")
            .and_then(|s| s.parse::<u32>().ok())
        {
            return self.fd_target(n).map(str::to_string).ok_or_else(enoent);
        }
        if inode_of(rel).is_some() {
            return Err(einval()); // not a symlink
        }
        Err(enoent())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Read an entire file by looping `read_at` to EOF.
    fn read_all(fs: &mut ProcFs, path: &str) -> Vec<u8> {
        let mut out = Vec::new();
        let mut off = 0u64;
        let mut buf = [0u8; 64];
        loop {
            let n = fs.read_at(path, off, &mut buf).unwrap();
            if n == 0 {
                break;
            }
            out.extend_from_slice(&buf[..n]);
            off += n as u64;
        }
        out
    }

    /// A fully populated sample, exercising every field the kernel is meant
    /// to eventually inject.
    fn sample() -> ProcData {
        ProcData {
            cmdline: b"prog\0--flag\0".to_vec(),
            exe: "/usr/bin/prog".to_string(),
            cwd: "/home/user".to_string(),
            maps: String::new(),
            comm: "prog".to_string(),
            argv0: "prog".to_string(),
            pid: 42,
            ppid: 7,
            uid: 1000,
            gid: 1000,
            state: 'R',
            threads: 3,
            vm_size_kb: 8192,
            vm_rss_kb: 2048,
            fds: vec![
                (0, "/dev/tty".to_string()),
                (1, "/dev/tty".to_string()),
                (2, "pipe:[12345]".to_string()),
            ],
            nproc: 4,
            auxv: Vec::new(),
        }
    }

    #[test]
    fn version_contains_linux() {
        let mut fs = ProcFs::new();
        let data = read_all(&mut fs, "version");
        assert!(String::from_utf8_lossy(&data).contains("Linux"));
    }

    #[test]
    fn root_readdir_lists_files_and_dirs() {
        let mut fs = ProcFs::new();
        let names: Vec<String> = fs
            .readdir("")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(names.contains(&"cpuinfo".to_string()));
        assert!(names.contains(&"self".to_string()));
        assert!(names.contains(&"sys".to_string()));
        // Default ProcData carries pid 1, so its numeric alias is listed too.
        assert!(names.contains(&"1".to_string()));
    }

    #[test]
    fn self_exe_is_a_symlink() {
        let mut fs = ProcFs::new();
        let attrs = fs.stat("self/exe").unwrap();
        assert_eq!(attrs.kind, NodeKind::Symlink);
        assert_eq!(attrs.mode, S_IFLNK | 0o777);
        // readlink resolves to the exe path.
        assert_eq!(fs.readlink("self/exe").unwrap(), "/bin/busybox");
    }

    #[test]
    fn set_self_changes_cmdline() {
        let mut fs = ProcFs::new();
        // Placeholder cmdline is empty.
        assert!(read_all(&mut fs, "self/cmdline").is_empty());
        fs.set_self(sample());
        assert_eq!(read_all(&mut fs, "self/cmdline"), b"prog\0--flag\0");
        assert_eq!(fs.readlink("self/exe").unwrap(), "/usr/bin/prog");
        let comm = read_all(&mut fs, "self/comm");
        assert_eq!(comm, b"prog\n");
    }

    #[test]
    fn directories_and_inodes() {
        let mut fs = ProcFs::new();
        assert_eq!(fs.stat("").unwrap().kind, NodeKind::Dir);
        assert_eq!(fs.stat("sys/kernel").unwrap().kind, NodeKind::Dir);
        assert_eq!(fs.stat("sys/kernel").unwrap().mode, S_IFDIR | 0o555);
        // Distinct inodes across entries.
        assert_ne!(
            fs.stat("cpuinfo").unwrap().inode,
            fs.stat("meminfo").unwrap().inode
        );
        // A regular file reports its rendered size.
        let meminfo = read_all(&mut fs, "meminfo");
        assert_eq!(fs.stat("meminfo").unwrap().size, meminfo.len() as u64);
        assert_eq!(fs.stat("meminfo").unwrap().mode, S_IFREG | 0o444);
    }

    #[test]
    fn unknown_path_errors() {
        let mut fs = ProcFs::new();
        assert!(fs.stat("nope").is_none());
        let mut buf = [0u8; 8];
        assert_eq!(
            fs.read_at("nope", 0, &mut buf).unwrap_err().raw_os_error(),
            Some(2)
        );
        assert_eq!(fs.readdir("nope").unwrap_err().raw_os_error(), Some(2));
    }

    #[test]
    fn read_only_backend() {
        assert!(ProcFs::new().read_only());
    }

    #[test]
    fn meminfo_contains_expected_fields() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "meminfo")).unwrap();
        assert!(text.contains("MemTotal:"));
        assert!(text.contains("MemFree:"));
    }

    #[test]
    fn self_status_reflects_injected_data() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        let text = String::from_utf8(read_all(&mut fs, "self/status")).unwrap();
        assert!(text.contains("Name:\tprog"));
        assert!(text.contains("Pid:\t42"));
        assert!(text.contains("PPid:\t7"));
        assert!(text.contains("Uid:\t1000\t1000\t1000\t1000"));
        assert!(text.contains("Gid:\t1000\t1000\t1000\t1000"));
        assert!(text.contains("Threads:\t3"));
        assert!(text.contains("VmSize:\t8192 kB"));
        assert!(text.contains("VmRSS:\t2048 kB"));
        assert!(text.contains("State:\tR (running)"));
    }

    #[test]
    fn self_stat_has_pid_and_comm() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        let text = String::from_utf8(read_all(&mut fs, "self/stat")).unwrap();
        assert!(text.starts_with("42 (prog) R 7 "));
        assert_eq!(text.split_whitespace().count(), 52);
    }

    #[test]
    fn pid_dir_mirrors_self() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        assert_eq!(read_all(&mut fs, "42/cmdline"), b"prog\0--flag\0");
        assert_eq!(fs.readlink("42/exe").unwrap(), "/usr/bin/prog");
        assert_eq!(fs.stat("42").unwrap().kind, NodeKind::Dir);
        let names: Vec<String> = fs
            .readdir("42")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(names.contains(&"fd".to_string()));
    }

    #[test]
    fn self_cwd_is_a_symlink() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        assert_eq!(fs.stat("self/cwd").unwrap().kind, NodeKind::Symlink);
        assert_eq!(fs.readlink("self/cwd").unwrap(), "/home/user");
    }

    #[test]
    fn self_fd_lists_injected_descriptors() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        assert_eq!(fs.stat("self/fd").unwrap().kind, NodeKind::Dir);
        let names: Vec<String> = fs
            .readdir("self/fd")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert_eq!(names.len(), 3);
        assert!(names.contains(&"0".to_string()));
        assert!(names.contains(&"2".to_string()));
        assert_eq!(fs.readlink("self/fd/2").unwrap(), "pipe:[12345]");
        assert_eq!(fs.stat("self/fd/0").unwrap().kind, NodeKind::Symlink);
    }

    #[test]
    fn self_fd_unknown_descriptor_is_enoent() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        assert_eq!(
            fs.readlink("self/fd/99").unwrap_err().raw_os_error(),
            Some(2)
        );
        assert!(fs.stat("self/fd/99").is_none());
    }

    #[test]
    fn self_maps_falls_back_to_default_when_not_injected() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "self/maps")).unwrap();
        assert!(text.contains("[stack]"));
        assert!(text.contains("[heap]"));
        assert!(text.contains("/bin/busybox"));
    }

    #[test]
    fn self_auxv_is_empty_by_default() {
        let mut fs = ProcFs::new();
        assert!(read_all(&mut fs, "self/auxv").is_empty());
    }

    #[test]
    fn cpuinfo_and_stat_track_nproc() {
        let mut fs = ProcFs::new();
        fs.set_self(sample()); // nproc = 4
        let cpuinfo = String::from_utf8(read_all(&mut fs, "cpuinfo")).unwrap();
        assert_eq!(cpuinfo.matches("processor\t:").count(), 4);
        let stat = String::from_utf8(read_all(&mut fs, "stat")).unwrap();
        assert!(stat.contains("cpu0 "));
        assert!(stat.contains("cpu3 "));
        assert!(!stat.contains("cpu4 "));
    }

    #[test]
    fn sys_kernel_files_present() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "sys/kernel/hostname")).unwrap();
        assert_eq!(text, "nixvm\n");
        let pid_max = String::from_utf8(read_all(&mut fs, "sys/kernel/pid_max")).unwrap();
        assert_eq!(pid_max, "32768\n");
    }

    #[test]
    fn net_tcp_has_expected_header() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "net/tcp")).unwrap();
        assert!(text.contains("sl"));
        assert!(text.contains("local_address"));
        assert!(text.contains("rem_address"));
        assert!(text.contains("st"));
        assert!(text.contains("uid"));
        assert!(text.contains("inode"));
    }

    #[test]
    fn net_dev_has_headers_and_lo_row() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "net/dev")).unwrap();
        assert!(text.contains("Inter-|"));
        assert!(text.contains("face |bytes"));
        assert!(text.contains("lo:"));
    }

    #[test]
    fn net_unix_has_expected_header() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "net/unix")).unwrap();
        assert!(text.starts_with("Num"));
        assert!(text.contains("RefCount"));
        assert!(text.contains("Protocol"));
        assert!(text.contains("Flags"));
        assert!(text.contains("Type"));
        assert!(text.contains("St"));
        assert!(text.contains("Inode"));
        assert!(text.contains("Path"));
    }

    #[test]
    fn net_directory_listing() {
        let mut fs = ProcFs::new();
        let names: Vec<String> = fs
            .readdir("net")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        for want in [
            "tcp",
            "tcp6",
            "udp",
            "udp6",
            "unix",
            "dev",
            "route",
            "snmp",
            "protocols",
        ] {
            assert!(names.contains(&want.to_string()), "missing {want}");
        }
        // Root readdir lists the new `net` directory.
        let root_names: Vec<String> = fs
            .readdir("")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(root_names.contains(&"net".to_string()));
    }

    #[test]
    fn sys_net_core_directory_listing() {
        let mut fs = ProcFs::new();
        let names: Vec<String> = fs
            .readdir("sys/net/core")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(names.contains(&"somaxconn".to_string()));
        let somaxconn = String::from_utf8(read_all(&mut fs, "sys/net/core/somaxconn")).unwrap();
        assert_eq!(somaxconn, "4096\n");
    }

    #[test]
    fn sys_net_ipv4_and_vm_and_fs_files() {
        let mut fs = ProcFs::new();
        assert_eq!(
            String::from_utf8(read_all(&mut fs, "sys/net/ipv4/tcp_rmem")).unwrap(),
            "4096\t131072\t6291456\n"
        );
        assert_eq!(
            String::from_utf8(read_all(&mut fs, "sys/vm/overcommit_memory")).unwrap(),
            "0\n"
        );
        assert_eq!(
            String::from_utf8(read_all(&mut fs, "sys/fs/file-max")).unwrap(),
            "1048576\n"
        );
    }

    #[test]
    fn self_statm_has_seven_numbers() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        let text = String::from_utf8(read_all(&mut fs, "self/statm")).unwrap();
        let fields: Vec<&str> = text.split_whitespace().collect();
        assert_eq!(fields.len(), 7);
        for f in &fields {
            assert!(f.parse::<u64>().is_ok(), "not a number: {f}");
        }
    }

    #[test]
    fn self_limits_contains_max_open_files() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "self/limits")).unwrap();
        assert!(text.contains("Max open files"));
        assert!(text.contains("Soft Limit"));
        assert!(text.contains("Hard Limit"));
    }

    #[test]
    fn self_io_and_oom_and_wchan() {
        let mut fs = ProcFs::new();
        let io = String::from_utf8(read_all(&mut fs, "self/io")).unwrap();
        assert!(io.contains("rchar:"));
        assert!(io.contains("read_bytes:"));
        assert_eq!(read_all(&mut fs, "self/oom_score"), b"0\n");
        assert_eq!(read_all(&mut fs, "self/oom_score_adj"), b"0\n");
        assert_eq!(read_all(&mut fs, "self/wchan"), b"0");
    }

    #[test]
    fn self_mountinfo_and_mounts() {
        let mut fs = ProcFs::new();
        let mountinfo = String::from_utf8(read_all(&mut fs, "self/mountinfo")).unwrap();
        assert!(mountinfo.contains(" / / "));
        assert!(mountinfo.contains(" - tmpfs tmpfs rw"));
        let mounts = String::from_utf8(read_all(&mut fs, "self/mounts")).unwrap();
        assert!(mounts.contains("tmpfs / tmpfs rw"));
    }

    #[test]
    fn self_smaps_tracks_maps() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "self/smaps")).unwrap();
        assert!(text.contains("[stack]"));
        assert!(text.contains("Rss:"));
        assert!(text.contains("VmFlags:"));
    }

    #[test]
    fn pid_alias_reaches_new_self_files() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        assert_eq!(read_all(&mut fs, "42/oom_score"), b"0\n");
        let statm = String::from_utf8(read_all(&mut fs, "42/statm")).unwrap();
        assert_eq!(statm.split_whitespace().count(), 7);
    }

    #[test]
    fn top_level_misc_files_present() {
        let mut fs = ProcFs::new();
        assert!(
            String::from_utf8(read_all(&mut fs, "diskstats"))
                .unwrap()
                .contains("vda")
        );
        assert!(
            String::from_utf8(read_all(&mut fs, "partitions"))
                .unwrap()
                .contains("#blocks")
        );
        assert!(
            String::from_utf8(read_all(&mut fs, "swaps"))
                .unwrap()
                .contains("Filename")
        );
        assert!(read_all(&mut fs, "modules").is_empty());
        assert!(
            String::from_utf8(read_all(&mut fs, "devices"))
                .unwrap()
                .contains("Character devices:")
        );
    }

    #[test]
    fn self_environ_contains_path() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "self/environ")).unwrap();
        assert!(text.contains("PATH="));
        // NUL-separated, as the kernel presents it.
        assert!(text.contains('\0'));
    }

    #[test]
    fn self_root_is_a_symlink_to_slash() {
        let mut fs = ProcFs::new();
        assert_eq!(fs.stat("self/root").unwrap().kind, NodeKind::Symlink);
        assert_eq!(fs.readlink("self/root").unwrap(), "/");
    }

    #[test]
    fn cpuinfo_contains_arch_feature_line() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "cpuinfo")).unwrap();
        assert!(text.contains("Features") || text.contains("flags"));
    }

    /// Checks the `8-4-4-4-12` hex shape `proc(5)` documents for
    /// `sys/kernel/random/{boot_id,uuid}`.
    fn is_uuid_shaped(s: &str) -> bool {
        let parts: Vec<&str> = s.split('-').collect();
        let widths = [8, 4, 4, 4, 12];
        parts.len() == widths.len()
            && parts
                .iter()
                .zip(widths)
                .all(|(p, w)| p.len() == w && p.chars().all(|c| c.is_ascii_hexdigit()))
    }

    #[test]
    fn random_uuid_matches_uuid_shape() {
        let mut fs = ProcFs::new();
        let uuid = String::from_utf8(read_all(&mut fs, "sys/kernel/random/uuid")).unwrap();
        assert!(is_uuid_shaped(uuid.trim()), "not UUID-shaped: {uuid}");
        let boot_id = String::from_utf8(read_all(&mut fs, "sys/kernel/random/boot_id")).unwrap();
        assert!(is_uuid_shaped(boot_id.trim()), "not UUID-shaped: {boot_id}");
    }

    #[test]
    fn random_entropy_and_poolsize() {
        let mut fs = ProcFs::new();
        assert_eq!(
            read_all(&mut fs, "sys/kernel/random/entropy_avail"),
            b"256\n"
        );
        assert_eq!(read_all(&mut fs, "sys/kernel/random/poolsize"), b"4096\n");
    }

    #[test]
    fn self_uid_map_contains_0_0() {
        let mut fs = ProcFs::new();
        let text = String::from_utf8(read_all(&mut fs, "self/uid_map")).unwrap();
        assert!(text.contains("0 0"));
        let text = String::from_utf8(read_all(&mut fs, "self/gid_map")).unwrap();
        assert!(text.contains("0 0"));
    }

    #[test]
    fn sys_kernel_extra_tunables_present() {
        let mut fs = ProcFs::new();
        assert_eq!(
            String::from_utf8(read_all(&mut fs, "sys/kernel/ngroups_max")).unwrap(),
            "65536\n"
        );
        assert_eq!(
            String::from_utf8(read_all(&mut fs, "sys/kernel/cap_last_cap")).unwrap(),
            "40\n"
        );
        assert!(
            String::from_utf8(read_all(&mut fs, "sys/kernel/threads-max"))
                .unwrap()
                .trim()
                .parse::<u64>()
                .is_ok()
        );
    }

    #[test]
    fn new_top_level_files_present() {
        let mut fs = ProcFs::new();
        assert!(read_all(&mut fs, "kallsyms").starts_with(b"0000000000000000"));
        assert!(read_all(&mut fs, "keys").is_empty());
        assert!(read_all(&mut fs, "key-users").is_empty());
        assert!(read_all(&mut fs, "locks").is_empty());
        let vmstat = String::from_utf8(read_all(&mut fs, "vmstat")).unwrap();
        assert!(vmstat.contains("nr_free_pages"));
        let zoneinfo = String::from_utf8(read_all(&mut fs, "zoneinfo")).unwrap();
        assert!(zoneinfo.contains("Node 0"));
        let buddyinfo = String::from_utf8(read_all(&mut fs, "buddyinfo")).unwrap();
        assert!(buddyinfo.contains("Node 0"));
        let consoles = String::from_utf8(read_all(&mut fs, "consoles")).unwrap();
        assert!(!consoles.is_empty());
    }

    #[test]
    fn self_sched_and_schedstat_and_personality() {
        let mut fs = ProcFs::new();
        fs.set_self(sample());
        let sched = String::from_utf8(read_all(&mut fs, "self/sched")).unwrap();
        assert!(sched.starts_with("prog (42, #threads: 3)"));
        assert_eq!(read_all(&mut fs, "self/schedstat"), b"0 0 0\n");
        assert_eq!(read_all(&mut fs, "self/personality"), b"0\n");
        assert_eq!(read_all(&mut fs, "self/setgroups"), b"allow\n");
    }

    #[test]
    fn new_listings_include_environ_and_random() {
        let mut fs = ProcFs::new();
        let self_names: Vec<String> = fs
            .readdir("self")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(self_names.contains(&"environ".to_string()));
        assert!(self_names.contains(&"root".to_string()));
        assert!(self_names.contains(&"sched".to_string()));
        assert!(self_names.contains(&"uid_map".to_string()));

        let kernel_names: Vec<String> = fs
            .readdir("sys/kernel")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(kernel_names.contains(&"random".to_string()));

        let random_names: Vec<String> = fs
            .readdir("sys/kernel/random")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(random_names.contains(&"uuid".to_string()));
        assert!(random_names.contains(&"boot_id".to_string()));

        let root_names: Vec<String> = fs
            .readdir("")
            .unwrap()
            .into_iter()
            .map(|e| e.name)
            .collect();
        assert!(root_names.contains(&"kallsyms".to_string()));
        assert!(root_names.contains(&"vmstat".to_string()));
    }
}