syd 3.52.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
//
// Syd: rock-solid application kernel
// src/test/util.rs: Utilities for integration tests
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

#![allow(clippy::disallowed_methods)]
#![allow(clippy::disallowed_types)]

use std::{
    env,
    error::Error,
    ffi::OsStr,
    fmt,
    fs::{canonicalize, File},
    io::Write,
    net::{Ipv6Addr, SocketAddrV6, TcpListener},
    os::fd::RawFd,
    path::{Path, PathBuf},
    process::{Child, Command, ExitStatus, Output, Stdio},
    sync::LazyLock,
    time::Duration,
};

use memchr::memmem;
use nix::{
    errno::Errno,
    sys::{
        resource::{Resource, RLIM_INFINITY},
        utsname::uname,
    },
    unistd::{isatty, Gid, Uid},
};
use syd::{config::*, confine::confine_rlimit};

#[derive(Debug)]
pub struct TestError(pub String);
pub type TestResult = Result<(), TestError>;

impl fmt::Display for TestError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl<E: Error> From<E> for TestError {
    fn from(err: E) -> Self {
        TestError(err.to_string())
    }
}

#[macro_export]
macro_rules! say {
    ($($arg:tt)*) => {{
        let msg = format!($($arg)*);
        let pre = "\r\x1b[K";

        if *$crate::util::SYD_TEST_TTY {
            eprint!("{pre}{msg}");
        } else {
            eprintln!("{msg}");
        }
    }};
}

#[macro_export]
macro_rules! assert {
    ($cond:expr) => {
        if !$cond {
            return Err(TestError(format!("Assertion failed: {}", stringify!($cond))));
        }
    };
    ($cond:expr, $($arg:tt)*) => {
        if !$cond {
            return Err(TestError(format!("Assertion failed: {}: {}", stringify!($cond), format_args!($($arg)*))));
        }
    };
}

#[macro_export]
macro_rules! assert_eq {
    ($left:expr, $right:expr) => {
        if $left != $right {
            return Err(TestError(format!("Assertion failed in {}:{}: (left: `{}`, right: `{}`)", file!(), line!(), $left, $right)));
        }
    };
    ($left:expr, $right:expr, $($arg:tt)*) => {
        if $left != $right {
            return Err(TestError(format!("Assertion failed in {}:{}: (left: `{}`, right: `{}`): {}", file!(), line!(), $left, $right, format_args!($($arg)*))));
        }
    };
}

#[macro_export]
macro_rules! assert_ne {
    ($left:expr, $right:expr) => {
        if $left == $right {
            return Err(TestError(format!("Assertion failed in {}:{}: (left: `{}`, right: `{}`)", file!(), line!(), $left, $right)));
        }
    };
    ($left:expr, $right:expr, $($arg:tt)*) => {
        if $left == $right {
            return Err(TestError(format!("Assertion failed in {}:{}: (left: `{}`, right: `{}`): {}", file!(), line!(), $left, $right, format_args!($($arg)*))));
        }
    };
}

#[macro_export]
macro_rules! fixup {
    ($cond:expr) => {
        if $cond {
            return Err(TestError(format!("Known issue fixed in {}:{}", file!(), line!())));
        } else {
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            eprintln!("Warning: Known issue still present in {}:{}", file!(), line!());
        }
    };
    ($cond:expr, $($arg:tt)*) => {
        if $cond {
            return Err(TestError(format!("Known issue fixed in {}:{}: {}", file!(), line!(), format_args!($($arg)*))));
        } else {
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            eprintln!("Warning: Known issue still present in {}:{}: {}", file!(), line!(), format_args!($($arg)*));
        }
    };
}

#[macro_export]
macro_rules! ignore {
    ($cond:expr) => {
        if $cond {
            eprintln!("Warning: Known issue fixed in {}:{}", file!(), line!());
        } else {
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            eprintln!("Warning: Known issue still present in {}:{}", file!(), line!());
        }
    };
    ($cond:expr, $($arg:tt)*) => {
        if $cond {
            eprintln!("Warning: Known issue fixed in {}:{}", file!(), line!());
        } else {
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            eprintln!("Warning: Known issue still present in {}:{}: {}", file!(), line!(), format_args!($($arg)*));
        }
    };
}

#[macro_export]
macro_rules! assert_status_aborted {
    ($status:expr) => {{
        const XABRT: i32 = 128 + libc::SIGABRT;
        const XBUS: i32 = 128 + libc::SIGBUS;
        const XILL: i32 = 128 + libc::SIGILL;
        const XSEGV: i32 = 128 + libc::SIGSEGV;
        assert_status_code_matches!($status, XABRT | XBUS | XILL | XSEGV);
    }};
}

#[macro_export]
macro_rules! assert_status_terminated {
    ($status:expr) => {{
        const XTERM: i32 = 128 + libc::SIGTERM;
        assert_status_code_matches!($status, XTERM);
    }};
}

#[macro_export]
macro_rules! assert_status_panicked {
    ($status:expr) => {{
        // If the main thread panics it will terminate all your threads
        // and end your program with code 101.
        // See: https://doc.rust-lang.org/std/macro.panic.html
        assert_status_code!($status, 101);
    }};
}

#[macro_export]
macro_rules! assert_status_timeout_exceeded {
    ($status:expr) => {{
        assert_status_code!($status, 124);
    }};
}

#[macro_export]
macro_rules! assert_status_code_matches {
    ($status:expr, $($pattern:tt)+) => {{
        let code = $status.code().unwrap_or(127);
        $crate::assert!(
            matches!(code, $($pattern)+),
            "code: {code} status: {:?}",
            $status
        );
    }};
}

#[macro_export]
macro_rules! assert_status_code {
    ($status:expr, $expected:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert_eq!(code, $expected, "code:{code} status:{:?}", $status);
    };
}

#[macro_export]
macro_rules! assert_status_ok {
    ($status:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert!($status.success(), "code:{code} status:{:?}", $status);
    };
}

#[macro_export]
macro_rules! assert_status_not_ok {
    ($status:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert!(!$status.success(), "code:{code} status:{:?}", $status);
    };
}

#[macro_export]
macro_rules! assert_status_bad_file {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EBADF);
    };
}

#[macro_export]
macro_rules! assert_status_bad_message {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EBADMSG);
    };
}

#[macro_export]
macro_rules! assert_status_access_denied {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EACCES);
    };
}

#[macro_export]
macro_rules! assert_status_permission_denied {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EPERM);
    };
}

#[macro_export]
macro_rules! assert_status_network_unreachable {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ENETUNREACH);
    };
}

#[macro_export]
macro_rules! assert_status_no_such_process {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ESRCH);
    };
}

#[macro_export]
macro_rules! assert_status_broken_pipe {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EPIPE);
    };
}

#[macro_export]
macro_rules! assert_status_busy {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EBUSY);
    };
}

#[macro_export]
macro_rules! assert_status_connection_refused {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ECONNREFUSED);
    };
}

#[macro_export]
macro_rules! assert_status_not_connected {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ENOTCONN);
    };
}

#[macro_export]
macro_rules! assert_status_faulted {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EFAULT);
    };
}

#[macro_export]
macro_rules! assert_status_hidden {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ENOENT);
    };
}

#[macro_export]
macro_rules! assert_status_notdir {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ENOTDIR);
    };
}

#[macro_export]
macro_rules! assert_status_illegal_sequence {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EILSEQ);
    };
}

#[macro_export]
macro_rules! assert_status_invalid {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EINVAL);
    };
}

#[macro_export]
macro_rules! assert_status_interrupted {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::EINTR);
    };
}

#[macro_export]
macro_rules! assert_status_loop {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ELOOP);
    };
}

#[macro_export]
macro_rules! assert_status_unimplemented {
    ($status:expr) => {
        $crate::assert_status_code!($status, libc::ENOSYS);
    };
}

#[macro_export]
macro_rules! assert_status_killed {
    ($status:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert_eq!(
            code,
            128 + libc::SIGKILL,
            "code:{code} status:{:?}",
            $status
        );
    };
}

#[macro_export]
macro_rules! assert_status_not_killed {
    ($status:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert_ne!(
            code,
            128 + libc::SIGKILL,
            "code:{code} status:{:?}",
            $status
        );
    };
}

#[macro_export]
macro_rules! assert_status_sigsys {
    ($status:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert_eq!(code, 128 + libc::SIGSYS, "code:{code} status:{:?}", $status);
    };
}

#[macro_export]
macro_rules! assert_status_signaled {
    ($status:expr, $signal:expr) => {
        let signal = $status.signal().unwrap_or(127);
        $crate::assert_eq!(signal, $signal, "signal:{signal} status:{:?}", $status);
    };
}

#[macro_export]
macro_rules! assert_status_not_supported {
    ($status:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert!(
            matches!(
                code,
                libc::EAFNOSUPPORT | libc::ENOTSUP | libc::EPROTONOSUPPORT
            ),
            "code:{code} status:{:?}",
            $status
        );
    };
}

#[macro_export]
macro_rules! assert_status_operation_not_supported {
    ($status:expr) => {
        let code = $status.code().unwrap_or(127);
        $crate::assert!(
            matches!(code, libc::EOPNOTSUPP),
            "code:{code} status:{:?}",
            $status
        );
    };
}

#[macro_export]
macro_rules! skip_unless_gnu {
    ($($program:expr),* $(,)?) => {{
        let mut all_gnu = true;
        $(
            if !is_program_gnu($program) {
                eprintln!("Test requires {} to be GNU, skipping!", $program);
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                all_gnu = false;
            }
        )*

        if !all_gnu {
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_available {
    ($($program:expr),* $(,)?) => {{
        let mut all_available = true;
        $(
            if !is_program_available($program) {
                eprintln!("Test requires {}, skipping!", $program);
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                all_available = false;
            }
        )*

        if !all_available {
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_trusted {
    () => {{
        if !cfg!(feature = "trusted") {
            eprintln!("trusted feature not enabled, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_if_32bin {
    () => {{
        if cfg!(target_pointer_width = "32") {
            eprintln!("32-bit target detected, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_if_32bin_64host {
    () => {{
        if check_32bin_64host() {
            eprintln!("Binary/Host mismatch, cannot run test, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_if_mips {
    () => {{
        if cfg!(any(
            target_arch = "mips",
            target_arch = "mips32r6",
            target_arch = "mips64",
            target_arch = "mips64r6",
        )) {
            eprintln!("Test does not work on MIPS, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_if_root {
    () => {{
        if Uid::effective().is_root() {
            eprintln!("Test requires to run as non-root user, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!("Thanks for not running this test as root!");
        }
    }};
}

#[macro_export]
macro_rules! skip_if_fs {
    ($($fs:expr),* $(,)?) => {{
        let cwd = open(".", OFlag::O_PATH | OFlag::O_DIRECTORY, Mode::empty()).unwrap();
        let current_fs = syd::compat::FsType::get(cwd).unwrap();
        $(
            if let Ok(fs_types) = syd::compat::FsType::from_name($fs) {
                if fs_types.contains(&current_fs) {
                    eprintln!("Test does not run correctly on {}, skipping!", $fs);
                    std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                    return Ok(());
                }
            }
        )*
        eprintln!("Filesystem check passed, continuing...");
    }};
}

#[macro_export]
macro_rules! skip_unless_iproute2 {
    () => {{
        if !check_iproute2() {
            eprintln!("ip is not iproute2, cannot run test, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_ipv6 {
    () => {{
        if !check_ipv6() {
            eprintln!("IPv6 is not supported, cannot run test, skipping!");
            env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_linux {
    ($need_major:expr, $need_minor:expr) => {{
        let (maj, min) = *syd::config::KERNEL_VERSION;
        let too_old = maj < $need_major || (maj == $need_major && min < $need_minor);
        if too_old {
            eprintln!(
                "Test requires Linux kernel >= {}.{} (current: {maj}.{min}), skipping!",
                $need_major, $need_minor,
            );
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!(
                "Linux kernel {maj}.{min} satisfies >= {}.{}, proceeding!",
                $need_major, $need_minor,
            );
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_stdin_is_a_tty {
    () => {{
        if !nix::unistd::isatty(std::io::stdin()).unwrap_or(false) {
            eprintln!("Test requires STDIN to be a TTY, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!("STDIN is a TTY, proceeding with test...");
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_stdout_is_a_tty {
    () => {{
        if !nix::unistd::isatty(std::io::stdout()).unwrap_or(false) {
            eprintln!("Test requires STDOUT to be a TTY, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!("STDOUT is a TTY, proceeding with test...");
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_kernel_crypto_is_supported {
    () => {{
        let key = syd::hash::Key::random().unwrap();
        let key_id = match syd::hash::add_key(
            "user",
            "SYD-3-CRYPT-TEST",
            key.as_ref(),
            syd::hash::KEY_SPEC_USER_KEYRING,
        ) {
            Ok(key_id) => key_id,
            Err(nix::errno::Errno::EAFNOSUPPORT | nix::errno::Errno::ENOSYS) => {
                eprintln!("Test requires Linux keyrings(7) API, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(nix::errno::Errno::EPERM) => {
                eprintln!("Are you in a container without keyrings access?");
                eprintln!("Test requires Linux keyrings(7) API, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(nix::errno::Errno::EACCES) => {
                eprintln!("Is your session keyring attached to your user keyring?");
                eprintln!("Test requires Linux keyrings(7) API, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(errno) => {
                return Err(TestError(format!(
                    "Failed to test for Linux keyrings(7) API: {errno}"
                )));
            }
        };
        match syd::hash::aes_ctr_setup(key_id) {
            Ok(fd) => drop(fd),
            Err(nix::errno::Errno::EAFNOSUPPORT | Errno::ENOPROTOOPT) => {
                eprintln!("Test requires Linux Kernel Cryptography API, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(nix::errno::Errno::EACCES) => {
                eprintln!("Is your session keyring attached to your user keyring?");
                eprintln!("Test requires Linux keyrings(7) API, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(errno) => {
                return Err(TestError(format!(
                    "Failed to test for Linux Kernel Cryptography API: {errno}"
                )));
            }
        }
        match syd::hash::hmac_sha256_setup(key_id) {
            Ok(fd) => drop(fd),
            Err(nix::errno::Errno::EAFNOSUPPORT | Errno::ENOPROTOOPT) => {
                eprintln!("Test requires Linux Kernel Cryptography API, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(nix::errno::Errno::EACCES) => {
                eprintln!("Is your session keyring attached to your user keyring?");
                eprintln!("Test requires Linux keyrings(7) API, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(errno) => {
                return Err(TestError(format!(
                    "Failed to test for Linux Kernel Cryptography API: {errno}"
                )));
            }
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_xattrs_are_supported {
    () => {{
        let fd = match nix::fcntl::open(
            "xattr.test",
            nix::fcntl::OFlag::O_WRONLY | nix::fcntl::OFlag::O_CREAT | nix::fcntl::OFlag::O_EXCL,
            nix::sys::stat::Mode::from_bits_truncate(0o600),
        ) {
            Ok(fd) => fd,
            Err(errno) => return Err(TestError(format!("Failed to open xattr.test: {errno}"))),
        };

        match syd::xattr::fsetxattr(&fd, "user.syd.crypt.api", b"3", libc::XATTR_CREATE) {
            Ok(_) => {
                let _ = nix::unistd::close(fd);
            }
            Err(nix::errno::Errno::EOPNOTSUPP) => {
                let _ = nix::unistd::close(fd);
                eprintln!("Test requires extended attributes support, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(errno) => {
                let _ = nix::unistd::close(fd);
                return Err(TestError(format!(
                    "Failed to test for extended attributes support: {errno}"
                )));
            }
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_unix_diag_is_supported {
    () => {{
        match syd::confine::check_unix_diag() {
            Ok(true) => {
                eprintln!("Unix socket diagnostics are supported, proceeding with test...");
            }
            Ok(false) => {
                eprintln!("Test requires UNIX socket diagnostics support, skipping!");
                std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
                return Ok(());
            }
            Err(errno) => {
                return Err(TestError(format!(
                    "Failed to test for UNIX socket diagnostics: {errno}"
                )));
            }
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_unshare {
    ( $( $ns:expr ),* $(,)? ) => {{
        // Build comma-separated namespace list.
        let namespaces = [$($ns),*].join(",");
        if namespaces.is_empty() {
            panic!("No namespace given!");
        }
        eprintln!("[*] Checking support for namespaces `{namespaces}'...");

        // Probe namespace support by running Syd.
        let code = syd()
            .p("off")
            .m(&format!("unshare/{namespaces}:1"))
            .arg("/dev/nulx")
            .status()
            .expect("execute syd")
            .code()
            .unwrap_or(127);
        if code != Errno::ENOENT as i32 {
            eprintln!("[!] Syd exited with {code}!");
            eprintln!("[!] Test requires Linux namespaces `{namespaces}', skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!("[*] Namespaces `{namespaces}' are supported, proceeding with test.");
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_coredumps {
    () => {{
        if let Err(errno) = enable_coredumps() {
            eprintln!("Failed to enable coredumps: {errno}!");
            eprintln!("Skipping test!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_exists {
    ($path:expr) => {{
        if !std::path::Path::new($path).exists() {
            eprintln!("Test requires the path \"{}\" to exist, skipping!", $path);
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_bitness {
    ($bitness:expr) => {{
        if !cfg!(target_pointer_width = $bitness) {
            eprintln!("Test requires a {}-bit syd, skipping!", $bitness);
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_ptrace_set_syscall_info {
    () => {{
        if !*syd::config::HAVE_PTRACE_SET_SYSCALL_INFO {
            eprintln!("Test requires PTRACE_SET_SYSCALL_INFO (Linux >= 6.14), skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_feature {
    ($feature:expr) => {{
        if !cfg!(feature = $feature) {
            eprintln!(
                "Test requires syd built with {} feature, skipping!",
                $feature
            );
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_cap {
    ($cap:expr) => {{
        use std::str::FromStr;
        let cap = syd::caps::Capability::from_str(&syd::caps::to_canonical($cap)).expect("cap2str");
        if !syd::caps::has_cap(None, syd::caps::CapSet::Permitted, cap).expect("syd::caps::has_cap")
        {
            eprintln!("Test requires {cap} capability, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!("Capability {cap} set, proceeding with test.");
        }
    }};
}

#[macro_export]
macro_rules! skip_if_landlock_abi_supported {
    ($abi:expr) => {{
        if syd::landlock::ABI::new_current() >= syd::landlock::ABI::from($abi) {
            eprintln!(
                "Test is for Landlock ABI versions older than {}, skipping!",
                $abi
            );
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!(
                "Landlock ABI {} is NOT supported, proceeding with test...",
                $abi
            );
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_landlock_abi_supported {
    ($abi:expr) => {{
        if syd::landlock::ABI::new_current() < syd::landlock::ABI::from($abi) {
            eprintln!("Test requires Landlock ABI version {}, skipping!", $abi);
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!(
                "Landlock ABI {} is supported, proceeding with test...",
                $abi
            );
        }
    }};
}

#[macro_export]
macro_rules! skip_if_cross_memory_attach_is_not_enabled {
    () => {
        if !*syd::config::HAVE_CROSS_MEMORY_ATTACH {
            eprintln!("skipping: kernel not configured with CONFIG_CROSS_MEMORY_ATTACH");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    };
}

#[macro_export]
macro_rules! skip_if_strace {
    () => {{
        if std::env::var("SYD_TEST_STRACE").is_ok() && std::env::var("SYD_TEST_FORCE").is_err() {
            eprintln!("Test does not work correctly under strace, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_strace_can_inject {
    () => {{
        if !check_strace_inject() {
            eprintln!("strace can't inject syscalls, cannot run test, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_pty {
    () => {{
        use std::process::Command;

        skip_unless_available!("python");

        // Run python to test for support.
        //
        // TODO: Make syd-tty do this.
        let status = Command::new("python")
            .arg("-c")
            .arg("import os; os.openpty()")
            .status()
            .expect("execute python");

        if status.code().unwrap_or(127) != 0 {
            eprintln!("Test requires PTY access, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        } else {
            eprintln!("PTY access is available, proceeding with test...");
        }
    }};
}

#[macro_export]
macro_rules! skip_unless_at_execve_check_is_supported {
    () => {{
        if !*HAVE_AT_EXECVE_CHECK {
            eprintln!("execveat(2) flag AT_EXECVE_CHECK is not supported, skipping!");
            std::env::set_var("SYD_TEST_SOFT_FAIL", "1");
            return Ok(());
        }
    }};
}

/// Holds a `String` to run `syd`.
/// Honours CARGO_BIN_EXE_syd environment variable.
pub static SYD: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd").unwrap_or("syd".to_string()));

/// Holds a `String` to run `syd-aux`.
/// Honours CARGO_BIN_EXE_syd-aux environment variable.
pub static SYD_AUX: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-aux").unwrap_or("syd-aux".to_string()));

/// Holds a `String` to run `syd-bit`.
/// Honours CARGO_BIN_EXE_syd-aux environment variable.
pub static SYD_BIT: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-bit").unwrap_or("syd-bit".to_string()));

/// Holds a `String` to run `syd-cap`.
/// Honours CARGO_BIN_EXE_syd-cap environment variable.
pub static SYD_CAP: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-cap").unwrap_or("syd-cap".to_string()));

/// Holds a `String` to run `syd-dns`.
/// Honours CARGO_BIN_EXE_syd-dns environment variable.
pub static SYD_DNS: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-dns").unwrap_or("syd-dns".to_string()));

/// Holds a `String` to run `syd-env`.
/// Honours CARGO_BIN_EXE_syd-env environment variable.
#[allow(dead_code)]
pub static SYD_ENV: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-env").unwrap_or("syd-env".to_string()));

/// Holds a `String` to run `syd-exec`.
/// Honours CARGO_BIN_EXE_syd-exec environment variable.
pub static SYD_EXEC: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-exec").unwrap_or("syd-exec".to_string()));

/// Holds a `String` to run `syd-aes`.
/// Honours CARGO_BIN_EXE_syd-aes environment variable.
pub static SYD_AES: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-aes").unwrap_or("syd-aes".to_string()));

/// Holds a `String` to run `syd-key`.
/// Honours CARGO_BIN_EXE_syd-key environment variable.
pub static _SYD_KEY: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-key").unwrap_or("syd-key".to_string()));

/// Holds a `String` to run `syd-elf`.
/// Honours CARGO_BIN_EXE_syd-elf environment variable.
pub static SYD_ELF: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-elf").unwrap_or("syd-elf".to_string()));

/// Holds a `String` to run `syd-cpu`.
/// Honours CARGO_BIN_EXE_syd-cpu environment variable.
pub static SYD_CPU: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-cpu").unwrap_or("syd-cpu".to_string()));

/// Holds a `String` to run `syd-hex`.
/// Honours CARGO_BIN_EXE_syd-hex environment variable.
pub static SYD_HEX: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-hex").unwrap_or("syd-hex".to_string()));

/// Holds a `String` to run `syd-info`.
/// Honours CARGO_BIN_EXE_syd-info environment variable.
pub static SYD_INFO: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-info").unwrap_or("syd-info".to_string()));

/// Holds a `String` to run `syd-lock`.
/// Honours CARGO_BIN_EXE_syd-lock environment variable.
pub static SYD_LOCK: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-lock").unwrap_or("syd-lock".to_string()));

/// Holds a `String` to run `syd-mdwe`.
/// Honours CARGO_BIN_EXE_syd-mdwe environment variable.
pub static SYD_MDWE: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-mdwe").unwrap_or("syd-mdwe".to_string()));

/// Holds a `String` to run `syd-ofd`.
/// Honours CARGO_BIN_EXE_syd-ofd environment variable.
pub static SYD_OFD: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-ofd").unwrap_or("syd-ofd".to_string()));

/// Holds a `String` to run `syd-pause`.
/// Honours CARGO_BIN_EXE_syd-pause environment variable.
pub static SYD_PAUSE: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-pause").unwrap_or("syd-pause".to_string()));

/// Holds a `String` to run `syd-pds`.
/// Honours CARGO_BIN_EXE_syd-pds environment variable.
pub static SYD_PDS: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-pds").unwrap_or("syd-pds".to_string()));

/// Holds a `String` to run `syd-sec`.
/// Honours CARGO_BIN_EXE_syd-sec environment variable.
pub static SYD_SEC: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-sec").unwrap_or("syd-sec".to_string()));

/// Holds a `String` to run `syd-size`.
/// Honours CARGO_BIN_EXE_syd-size environment variable.
pub static SYD_SIZE: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-size").unwrap_or("syd-size".to_string()));

/// Holds a `String` to run `syd-test-do`.
/// Honours CARGO_BIN_EXE_syd-test-do environment variable.
/// This path is a canonicalized for ease of use in sandboxing tests.
pub static SYD_DO: LazyLock<String> =
    LazyLock::new(|| match env::var("CARGO_BIN_EXE_syd-test-do") {
        Ok(var) => Path::new(&var)
            .canonicalize()
            .expect("CARGO_BIN_EXE_syd-test-do")
            .to_string_lossy()
            .into_owned(),
        Err(_) => which(if env::var("SYD_TEST_32").is_ok() {
            "syd-test-do32"
        } else {
            "syd-test-do"
        })
        .expect("syd-test-do"),
    });

/// Holds a `String` to run `syd-uts`.
/// Honours CARGO_BIN_EXE_syd-uts environment variable.
pub static SYD_UTS: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-uts").unwrap_or("syd-uts".to_string()));

/// Holds a `String` to run `syd-x`.
/// Honours CARGO_BIN_EXE_syd-x environment variable.
pub static SYD_X: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-x").unwrap_or("syd-x".to_string()));

#[cfg(feature = "oci")]
/// Holds a `String` to run `syd-oci`.
/// Honours CARGO_BIN_EXE_syd-oci environment variable.
pub static SYD_OCI: LazyLock<String> =
    LazyLock::new(|| env::var("CARGO_BIN_EXE_syd-oci").unwrap_or("syd-oci".to_string()));

/// A boolean which specifies if we're running under SourceHut CI.
pub static CI_BUILD: LazyLock<bool> = LazyLock::new(|| env::var("JOB_ID").ok().is_some());

/// A boolean which specifies if we're running under GitLab CI.
pub static GL_BUILD: LazyLock<bool> = LazyLock::new(|| env::var("CI_PROJECT_ID").ok().is_some());

/// A boolean which specifies whether standard error is a TTY.
#[allow(dead_code)]
pub static SYD_TEST_TTY: LazyLock<bool> =
    LazyLock::new(|| isatty(std::io::stderr()).unwrap_or(false));

pub struct Syd {
    cmd: Command,
    is_quiet: bool,
}

impl Syd {
    pub fn new(cmd: &str) -> Self {
        let mut cmd = Command::new(cmd);

        cmd.stdin(Stdio::null());

        Syd {
            cmd,
            is_quiet: false,
        }
    }

    pub fn c<S: ToString>(&mut self, arg: S) -> &mut Self {
        self.cmd.arg(format!("-c{}", arg.to_string()));
        self
    }

    pub fn m<S: ToString>(&mut self, arg: S) -> &mut Self {
        self.cmd.arg(format!("-m{}", arg.to_string()));
        self
    }

    pub fn p<S: ToString>(&mut self, arg: S) -> &mut Self {
        self.cmd.arg(format!("-p{}", arg.to_string()));
        self
    }

    #[expect(non_snake_case)]
    pub fn P<S: ToString>(&mut self, arg: S) -> &mut Self {
        self.cmd.arg(format!("-P{}", arg.to_string()));
        self
    }

    pub fn current_dir<S: ToString>(&mut self, arg: S) -> &mut Self {
        self.cmd.current_dir(arg.to_string());
        self
    }

    pub fn log(&mut self, value: &str) -> &mut Self {
        self.cmd
            .env(ENV_LOG, env::var(ENV_LOG).unwrap_or(value.to_string()));
        self
    }

    pub fn log_fd(&mut self, fd: RawFd) -> &mut Self {
        self.cmd.env(ENV_LOG_FD, fd.to_string());
        self
    }

    pub fn do_<I, S, V>(&mut self, value: V, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.cmd.args(["--", &SYD_DO]);
        self.cmd.args(args);
        self.do__(value)
    }

    pub fn do__<V>(&mut self, value: V) -> &mut Self
    where
        V: AsRef<OsStr>,
    {
        self.cmd.env("SYD_TEST_DO", value);
        self
    }

    pub fn argv<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.cmd.arg("--");
        self.cmd.args(args);
        self
    }

    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
        self.cmd.arg(arg);
        self
    }

    pub fn args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<std::ffi::OsStr>,
    {
        self.cmd.args(args);
        self
    }

    pub fn stdin(&mut self, cfg: Stdio) -> &mut Self {
        self.cmd.stdin(cfg);
        self
    }

    pub fn stdout(&mut self, cfg: Stdio) -> &mut Self {
        self.cmd.stdout(cfg);
        self
    }

    pub fn stderr(&mut self, cfg: Stdio) -> &mut Self {
        self.cmd.stderr(cfg);
        self
    }

    #[allow(dead_code)]
    pub fn quiet(&mut self) -> &mut Self {
        self.stderr(Stdio::null());
        self.stdout(Stdio::null());
        self.is_quiet = true;
        self
    }

    pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        self.cmd.env(key, value);
        self
    }

    pub fn env_remove<K>(&mut self, key: K) -> &mut Self
    where
        K: AsRef<OsStr>,
    {
        self.cmd.env_remove(key);
        self
    }

    pub fn spawn(&mut self) -> std::io::Result<Child> {
        if !self.is_quiet {
            eprintln!("\x1b[93m+ {:?}\x1b[0m", self.cmd);
        }
        self.cmd.spawn()
    }

    pub fn status(&mut self) -> std::io::Result<ExitStatus> {
        if !self.is_quiet {
            eprintln!("\x1b[93m+ {:?}\x1b[0m", self.cmd);
        }
        self.cmd.status()
    }

    pub fn output(&mut self) -> std::io::Result<Output> {
        if !self.is_quiet {
            eprintln!("\x1b[93m+ {:?}\x1b[0m", self.cmd);
        }

        // With `output` stderr defaults to `piped`.
        self.cmd.stderr(Stdio::inherit());

        self.cmd.output()
    }
}

/// Returns a `Command` to run `syd`.
/// Honours CARGO_BIN_EXE_syd environment variable.
pub fn syd() -> Syd {
    static USE_PERF: LazyLock<bool> = LazyLock::new(|| env::var_os("SYD_TEST_PERF").is_some());
    static USE_TRACE: LazyLock<bool> = LazyLock::new(|| env::var_os("SYD_TEST_TRACE").is_some());
    static USE_STRACE: LazyLock<bool> = LazyLock::new(|| env::var_os("SYD_TEST_STRACE").is_some());
    static USE_VALGRIND: LazyLock<bool> =
        LazyLock::new(|| env::var_os("SYD_TEST_VALGRIND").is_some());
    static USE_HELGRIND: LazyLock<bool> =
        LazyLock::new(|| env::var_os("SYD_TEST_HELGRIND").is_some());
    let mut cmd = Syd::new("timeout");
    if check_timeout_foreground() {
        // Use -v, not --verbose.
        // Latter is not supported by Android.
        cmd.arg("-v");
        cmd.arg("--foreground");
        cmd.arg("--preserve-status");
    }
    cmd.arg("-sKILL");
    cmd.arg(env::var("SYD_TEST_TIMEOUT").unwrap_or("15m".to_string()));
    if *USE_PERF {
        cmd.arg("perf");
        cmd.arg("record");
        cmd.arg("-F99");
        cmd.arg("--call-graph=dwarf");
        cmd.arg("-o/tmp/syd-perf.data"); // FIXME
        cmd.arg("--");
    } else if *USE_STRACE {
        cmd.arg("strace");
        cmd.arg("-yyY");

        if env::var_os("SYD_TEST_STRACE_NOFORK").is_none() {
            cmd.arg("-f");
        }

        if env::var_os("SYD_TEST_STRACE_VERBOSE").is_none() {
            cmd.arg("-s256");
            cmd.arg("-e!read,readv,write,writev");
        } else {
            cmd.arg("-s4096");
        }

        let arg = env::var_os("SYD_TEST_STRACE").unwrap();
        if !arg.is_empty() {
            cmd.arg(arg);
        }

        cmd.arg("--");
    } else if *USE_VALGRIND {
        cmd.arg("valgrind");
        cmd.arg("--leak-check=yes");
        cmd.arg("--track-origins=yes");
        cmd.arg("--track-fds=yes");
        cmd.arg("--trace-children=no");
        cmd.arg("--");
    } else if *USE_HELGRIND {
        cmd.arg("valgrind");
        cmd.arg("--tool=helgrind");
        cmd.arg("--");
    }
    cmd.arg(&*SYD);
    // To get meaningful panics:
    // 1. Set quick boot to on.
    // 2. Set as dumpable.
    cmd.arg("-q");
    cmd.m("trace/allow_unsafe_dumpable:1");
    // Set logging level to warning.
    // Allow user to override.
    cmd.env(ENV_LOG, env::var(ENV_LOG).unwrap_or("warn".to_string()));
    // Quiet TTY output to avoid noisy test logs.
    // Unless otherwise specified.
    if env::var_os(ENV_FORCE_TTY).is_none() {
        cmd.env(ENV_QUIET_TTY, "YesPlease");
    }
    // Allow coredumps and non-PIE.
    cmd.m("trace/allow_unsafe_exec_nopie:1"); // Allow non-PIE execution.
    cmd.m("trace/allow_unsafe_prlimit:1"); // Allow coredumps.
    if *USE_TRACE || (*USE_STRACE && env::var_os("SYD_TEST_STRACE_NOFORK").is_none()) {
        cmd.m("trace/allow_unsafe_ptrace:1"); // Disable ptrace.
    }
    cmd
}

/// Check UID of a user using id(1).
pub fn get_user_uid(user: &str) -> Uid {
    let out = Command::new("id")
        .arg("-u")
        .arg(user)
        .output()
        .unwrap()
        .stdout;
    let out = String::from_utf8_lossy(&out);
    let out = out.trim();
    Uid::from(out.parse::<libc::uid_t>().unwrap())
}

/// Check GID of a user using id(1).
pub fn get_user_gid(user: &str) -> Gid {
    let out = Command::new("id")
        .arg("-g")
        .arg(user)
        .output()
        .unwrap()
        .stdout;
    let out = String::from_utf8_lossy(&out);
    let out = out.trim();
    Gid::from(out.parse::<libc::gid_t>().unwrap())
}

/// Check if the given program is of GNU flavour.
pub fn is_program_gnu(command: &str) -> bool {
    if check_32bin_64host() {
        eprintln!("Binary/Host mismatch, cannot use program {command}!");
        return false;
    }

    // Check if `command --version` returns GNU substring.
    let out = Command::new(command)
        .arg("--version")
        .output()
        .unwrap()
        .stdout;
    memmem::find(&out, b"GNU").is_some()
}

/// 0. Check if there's a binary/host mismatch.
/// 1. Check if a program exists in PATH
pub fn is_program_available(command: &str) -> bool {
    if check_32bin_64host() {
        eprintln!("Binary/Host mismatch, cannot use program {command}!");
        return false;
    }

    // Check if the command exists in PATH
    Command::new("which")
        .stdout(Stdio::null())
        .arg(command)
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

/// Resembles the `which` command, finds a program in PATH.
pub fn which(command: &str) -> Result<String, Errno> {
    let out = Command::new("which")
        .arg(command)
        .output()
        .expect("execute which")
        .stdout;
    if out.is_empty() {
        return Err(Errno::ENOENT);
    }

    let bin = String::from_utf8_lossy(&out);
    let bin = bin.trim();
    Ok(canonicalize(bin)
        .map_err(|_| Errno::last())?
        .to_string_lossy()
        .into_owned())
}

/// Check if IPv6 is supported
pub fn check_ipv6() -> bool {
    // Preliminary check for IPv6 availability
    let test_sock = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0);
    if let Err(error) = TcpListener::bind(test_sock) {
        eprintln!("IPv6 is not available on this system. Skipping test: {error}");
        false
    } else {
        true
    }
}

/// Checks if the C compiler allows nested routines.
/// Returns `true` if supported, `false` otherwise.
/// If successful, creates the executable `nested` in CWD.
/// See: https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html
pub fn check_nested_routines() -> bool {
    let c_code = r#"
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int x = atoi(argv[1]);
    int nested()
    {
        return x * x;
    };

    // Use pointer indirection so compiler cannot unnest.
    int (*fp)() = nested;

    // Yolo!
    return fp();
}
"#;
    if let Ok(mut file) = File::create("nested.c") {
        if file.write_all(c_code.as_bytes()).is_err() {
            return false;
        }
    } else {
        return false;
    }

    // Compile the C code using the C compiler
    let compile_status = Command::new("cc")
        .arg("-Wall")
        .arg("-Wextra")
        .arg("-zexecstack") // required on ppc64
        .arg("nested.c")
        .arg("-o")
        .arg("nested")
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status();

    // Return true if the compilation succeeded, false otherwise
    compile_status
        .map(|status| status.success())
        .unwrap_or(false)
}

/// Checks if the C compiler allows self-modifying code with mprotect.
/// Returns `true` if supported, `false` otherwise.
/// Only works on x86-64, always returns `false` on other architectures.
/// If successful, creates the executable `selfmod` in CWD.
/// See: https://shanetully.com/2013/12/writing-a-self-mutating-x86_64-c-program/
pub fn check_self_modifying_mp() -> bool {
    if !cfg!(target_arch = "x86_64") {
        return false;
    }

    let c_code = r#"
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>

void foo(void);
int change_page_permissions_of_address(void *addr);

int main(void) {
    void *foo_addr = (void*)foo;

    // Change the permissions of the page that contains foo() to read,
    // write, and execute. This assumes that foo() is fully contained
    // by a single page.
    if(change_page_permissions_of_address(foo_addr) == -1) {
        int save_errno = errno;
        fprintf(stderr, "Error while changing page permissions of foo(): %s!\n", strerror(errno));
        return save_errno;
    }

    // Call the unmodified foo()
    puts("Calling foo...");
    foo();

    // Change the immediate value in the addl instruction in foo() to 42
    unsigned char *instruction = (unsigned char*)foo_addr + 18;
    *instruction = 0x2A;

    // Call the modified foo()
    puts("Calling foo...");
    foo();

    return 0;
}

void foo(void) {
    int i=0;
    i++;
    printf("i: %d\n", i);
}

int change_page_permissions_of_address(void *addr) {
    // Move the pointer to the page boundary
    int page_size = getpagesize();
    addr -= (unsigned long)addr % page_size;

    if(mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) {
        return -1;
    }

    return 0;
}
"#;
    if let Ok(mut file) = File::create("selfmod.c") {
        if file.write_all(c_code.as_bytes()).is_err() {
            return false;
        }
    } else {
        return false;
    }

    // Compile the C code using the C compiler.
    let compile_status = Command::new("cc")
        .arg("-std=c99")
        .arg("-D_BSD_SOURCE")
        .arg("-Wall")
        .arg("selfmod.c")
        .arg("-o")
        .arg("selfmod")
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status();

    // Return true if the compilation succeeded, false otherwise.
    compile_status
        .map(|status| status.success())
        .unwrap_or(false)
}

/// Checks if the C compiler allows self-modifying code with executable stack.
/// Returns `true` if supported, `false` otherwise.
/// Only works on x86-64, always returns `false` on other architectures.
/// If successful, creates the executable `selfmod` in CWD.
/// See: https://shanetully.com/2013/12/writing-a-self-mutating-x86_64-c-program/
pub fn check_self_modifying_xs() -> bool {
    if !cfg!(target_arch = "x86_64") {
        return false;
    }

    let c_code = r#"
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>

void foo(void);
int change_page_permissions_of_address(void *addr);

int main(void) {
    void *foo_addr = (void*)foo;

    // Change the permissions of the page that contains foo() to read,
    // write, and execute. This assumes that foo() is fully contained
    // by a single page.
    if(change_page_permissions_of_address(foo_addr) == -1) {
        int save_errno = errno;
        fprintf(stderr, "Error while changing page permissions of foo(): %s!\n", strerror(errno));
        return save_errno;
    }

    // Call the unmodified foo()
    puts("Calling foo...");
    foo();

    // Change the immediate value in the addl instruction in foo() to 42
    unsigned char *instruction = (unsigned char*)foo_addr + 18;
    *instruction = 0x2A;

    // Call the modified foo()
    puts("Calling foo...");
    foo();

    return 0;
}

void foo(void) {
    int i=0;
    i++;
    printf("i: %d\n", i);
}

int change_page_permissions_of_address(void *addr) {
    // Move the pointer to the page boundary
    int page_size = getpagesize();
    addr -= (unsigned long)addr % page_size;

    if(mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) {
        return -1;
    }

    return 0;
}
"#;
    if let Ok(mut file) = File::create("selfmod.c") {
        if file.write_all(c_code.as_bytes()).is_err() {
            return false;
        }
    } else {
        return false;
    }

    // Compile the C code using the C compiler.
    let compile_status = Command::new("cc")
        .arg("-std=c99")
        .arg("-D_BSD_SOURCE")
        .arg("-zexecstack")
        .arg("-Wall")
        .arg("selfmod.c")
        .arg("-o")
        .arg("selfmod")
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status();

    // Return true if the compilation succeeded, false otherwise.
    compile_status
        .map(|status| status.success())
        .unwrap_or(false)
}

/// Format a `Duration` into a human readable `String`.
pub fn format_duration(d: Duration) -> String {
    let total_seconds = d.as_secs();
    let hours = total_seconds / 3600;
    let minutes = (total_seconds % 3600) / 60;
    let seconds = total_seconds % 60;

    format!("{hours}h {minutes}m {seconds}s")
}

/// Checks if the current running binary is 32-bit and the host system is 64-bit.
pub fn check_32bin_64host() -> bool {
    // Check if the current binary is 32-bit using a compile-time constant.
    // This constant is set by the Cargo build script based on the target architecture.
    #[cfg(target_pointer_width = "32")]
    let is_binary_32bit = true;
    #[cfg(not(target_pointer_width = "32"))]
    let is_binary_32bit = false;

    // Use uname to check if the host is 64-bit.
    let arch = uname()
        .expect("uname")
        .machine()
        .to_string_lossy()
        .to_string();

    if is_binary_32bit && arch.contains("64") {
        eprintln!("32->64: Running 32bit on {arch}!");
        true
    } else {
        false
    }
}

/// Checks whether strace supports syscall injection.
pub fn check_strace_inject() -> bool {
    let status = Command::new("strace")
        .arg("-qq")
        .arg("-e")
        .arg("trace=getpid")
        .arg("-e")
        .arg("inject=getpid:retval=2525")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg("test $$ -eq 2525")
        .status();

    match status {
        Ok(status) => status.success(),
        Err(_) => false,
    }
}

/// Enable coredumps.
pub fn enable_coredumps() -> Result<(), Errno> {
    // Set both the soft and hard limits
    confine_rlimit(Resource::RLIMIT_CORE, Some(RLIM_INFINITY))
}

/// Check if timeout --foreground is supported.
pub fn check_timeout_foreground() -> bool {
    Command::new("timeout")
        .arg("--foreground")
        .arg("-sKILL")
        .arg("60s")
        .arg("true")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

/// Check if the `ip` command is of `iproute2` (not `busybox`).
pub fn check_iproute2() -> bool {
    Command::new("sh")
        .arg("-cex")
        .arg("ip -V | grep -iq iproute2")
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

/// Retrieves the current directory or its basename as a `PathBuf`, based on the `base` parameter.
pub fn current_dir(base: bool) -> std::io::Result<PathBuf> {
    // Get the current working directory
    let current_dir = env::current_dir()?;

    if base {
        // Extract the basename
        let basename = current_dir
            .file_name()
            .ok_or(std::io::Error::other("Failed to get the basename"))
            .map(PathBuf::from)?;

        Ok(basename)
    } else {
        // Return the full path as PathBuf
        current_dir.canonicalize()
    }
}

/// Shuffles a vector using the Fisher-Yates algorithm,
/// utilizing random numbers obtained via `libc::rand`.
/// On Android, falls back to `syd::rng::randint`.
///
/// # Arguments
/// * `vec` - A mutable reference to the vector to shuffle.
pub fn shuffle_vec<T>(vec: &mut [T]) {
    let len = vec.len();
    for i in 0..len {
        // Android does not define libc::rand().
        #[cfg(not(target_os = "android"))]
        let r = unsafe { libc::rand() } as usize;
        #[cfg(target_os = "android")]
        let r = syd::rng::randint(usize::MIN..=usize::MAX).unwrap();

        let j = r % (len - i) + i;
        vec.swap(i, j); // Perform the swap.
    }
}