syd 3.42.0

rock-solid application kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
//
// Syd: rock-solid application kernel
// src/req.rs: seccomp(2) notify request handling
//
// Copyright (c) 2023, 2024, 2025 Ali Polatel <alip@chesswob.org>
// Based in part upon greenhook which is under public domain.
//
// SPDX-License-Identifier: GPL-3.0

use std::{
    cmp::Ordering,
    collections::hash_map::Entry,
    ffi::CString,
    fs::File,
    io,
    io::{IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write},
    ops::Deref,
    os::{
        fd::{AsFd, AsRawFd, OwnedFd, RawFd},
        unix::ffi::OsStrExt,
    },
    sync::{Arc, LazyLock, RwLock},
};

use bitflags::bitflags;
use data_encoding::HEXLOWER;
use libseccomp::{ScmpNotifResp, ScmpNotifRespFlags};
use memchr::memchr;
use nix::{
    errno::Errno,
    fcntl::{OFlag, ResolveFlag},
    sys::{
        signal::SaFlags,
        socket::UnixAddr,
        time::TimeSpec,
        uio::{process_vm_readv, process_vm_writev, RemoteIoVec},
    },
    unistd::Pid,
    NixPath,
};
use serde::{ser::SerializeMap, Serialize};

use crate::{
    compat::{fstatx, timespec_tv_nsec_t, TimeSpec32, TimeSpec64, STATX_INO, XATTR_NAME_MAX},
    config::{
        ENV_NO_CROSS_MEMORY_ATTACH, ENV_PROC_PID_MEM_FALLBACK, HAVE_CROSS_MEMORY_ATTACH,
        MMAP_MIN_ADDR, PROC_FILE,
    },
    confine::{op2name, scmp_arch_bits, ScmpNotifReq, SydArch, Sydcall, EIDRM},
    error,
    fs::{
        fd_status_flags, file_type, pidfd_getfd, pidfd_open, pidfd_send_signal, process_mrelease,
        safe_canonicalize, safe_open_msym, seccomp_notify_addfd, seccomp_notify_id_valid,
        to_valid_fd, unix_inodes, CanonicalPath, FileType, FsFlags, PIDFD_THREAD,
    },
    path::{XPath, XPathBuf, PATH_MAX, PATH_MIN},
    proc::{
        proc_auxv, proc_maps, proc_rand_fd, proc_stack_pointer, proc_status, proc_tgid,
        proc_unix_inodes,
    },
    sandbox::{Action, Flags, Sandbox, SandboxGuard},
    workers::{aes::AesLock, UnixMap, UnixVal, WorkerCache},
};

/*
 * Macros
 */
bitflags! {
    /// Flags for `SysArg`.
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
    pub(crate) struct SysFlags: u8 {
        /// Whether if it's ok for the path to be empty.
        const EMPTY_PATH = 1 << 0;
    }
}

impl Serialize for SysFlags {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut flags: Vec<&str> = vec![];

        if self.is_empty() {
            return serializer.collect_seq(flags);
        }

        if self.contains(Self::EMPTY_PATH) {
            flags.push("empty-path");
        }

        flags.sort();
        serializer.collect_seq(flags)
    }
}

/// `SysArg` represents a system call path argument,
/// coupled with a directory file descriptor as necessary.
#[derive(Copy, Clone, Debug, Default)]
pub(crate) struct SysArg {
    /// DirFd index in syscall args, if applicable.
    pub(crate) dirfd: Option<usize>,
    /// Path index in syscall args, if applicable.
    pub(crate) path: Option<usize>,
    /// Options for the system call.
    pub(crate) flags: SysFlags,
    /// Options for path canonicalization.
    pub(crate) fsflags: FsFlags,
    /// Whether dot as final component must return the given `Errno`.
    pub(crate) dotlast: Option<Errno>,
}

impl Serialize for SysArg {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(Some(5))?;
        map.serialize_entry("dirfd", &self.dirfd)?;
        map.serialize_entry("path", &self.path)?;
        map.serialize_entry("flags", &self.flags)?;
        map.serialize_entry("fsflags", &self.fsflags)?;
        map.serialize_entry("dotlast", &self.dotlast.map(|e| e as i32))?;
        map.end()
    }
}

impl SysArg {
    pub(crate) fn open(flags: OFlag, atfunc: bool, rflags: ResolveFlag) -> Self {
        let (dirfd, path) = if atfunc {
            (Some(0), Some(1))
        } else {
            (None, Some(0))
        };

        // SAFETY:
        // We do not resolve symbolic links if O_CREAT|O_EXCL is
        // specified to support creating files through dangling symbolic
        // links, see the creat_thru_dangling test for more information.
        // We also set MISS_LAST in this case so we get to assert EEXIST.
        let is_create = flags.contains(OFlag::O_CREAT);
        let is_exclusive_create = is_create && flags.contains(OFlag::O_EXCL);

        let mut fsflags = FsFlags::empty();
        if is_exclusive_create {
            fsflags.insert(FsFlags::MISS_LAST);
        } else if !is_create {
            fsflags.insert(FsFlags::MUST_PATH);
        };

        if flags.contains(OFlag::O_NOFOLLOW) || is_exclusive_create {
            fsflags |= FsFlags::NO_FOLLOW_LAST;
        }

        if rflags.contains(ResolveFlag::RESOLVE_BENEATH) {
            fsflags |= FsFlags::RESOLVE_BENEATH;
        }

        if rflags.contains(ResolveFlag::RESOLVE_NO_SYMLINKS) {
            fsflags |= FsFlags::NO_RESOLVE_PATH;
        }

        if rflags.contains(ResolveFlag::RESOLVE_NO_MAGICLINKS) {
            fsflags |= FsFlags::NO_RESOLVE_PROC;
        }

        if rflags.contains(ResolveFlag::RESOLVE_NO_XDEV) {
            fsflags |= FsFlags::NO_RESOLVE_XDEV;
        }

        Self {
            dirfd,
            path,
            fsflags,
            ..Default::default()
        }
    }
}

// Represents path arguments (max=2).
pub(crate) type PathArg<'a> = Option<CanonicalPath<'a>>;

#[derive(Debug)]
pub(crate) struct PathArgs<'a>(pub(crate) PathArg<'a>, pub(crate) PathArg<'a>);

/// By using `RemoteProcess`, you can get information about the
/// supervised process.
#[derive(Clone, Debug)]
pub struct RemoteProcess {
    /// The process ID.
    pub pid: Pid,
}

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

impl Eq for RemoteProcess {}

impl Ord for RemoteProcess {
    fn cmp(&self, other: &Self) -> Ordering {
        self.pid.cmp(&other.pid)
    }
}

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

impl RemoteProcess {
    /// Create a new `RemoteProcess` for the given TID.
    pub(crate) fn new(pid: Pid) -> Self {
        Self { pid }
    }

    /// Read path from the given system call argument with the given request.
    /// Check for magic prefix is magic is true.
    ///
    /// If `request` is `Some()` request is validated after
    /// actions that require validation such as proc reads
    /// and fd transfers. Otherwise, the caller must validate
    /// to verify the path read from sandbox process memory
    /// is what's expected.
    #[expect(clippy::cognitive_complexity)]
    #[expect(clippy::type_complexity)]
    pub(crate) fn read_path<'b>(
        &self,
        sandbox: &SandboxGuard,
        args: [u64; 6],
        arg: SysArg,
        mut magic: bool,
        request: Option<&UNotifyEventRequest>,
    ) -> Result<(CanonicalPath<'b>, bool, bool, bool), Errno> {
        let orig = match arg.path {
            Some(idx) => {
                // SAFETY: Check pointer against mmap_min_addr.
                if args[idx] < *MMAP_MIN_ADDR {
                    return Err(Errno::EFAULT);
                }

                Some(self.remote_path(args[idx], request)?)
            }
            None => None,
        };
        let mut doterr = false;

        // magic is both an in and out variable.
        // in=t: check for magic path.
        // out=t: path is magic path.
        let check_magic = magic;
        magic = false;

        let mut empty_path = false;
        let canonical_path = if let Some(path) = orig {
            empty_path = path.is_empty();
            if empty_path && !arg.flags.contains(SysFlags::EMPTY_PATH) {
                return Err(Errno::ENOENT);
            }

            if let Some(errno) = arg.dotlast {
                if path.ends_with_dot() {
                    if errno == Errno::ENOENT {
                        // This will be handled later, as we may
                        // need to return EEXIST instead of ENOENT
                        // if the path exists.
                        doterr = true;
                    } else {
                        return Err(errno);
                    }
                }
            }

            if check_magic && path.is_magic() {
                magic = true;
                CanonicalPath::new_magic(path)
            } else if empty_path || path.is_dot() {
                let dirfd = if let Some(idx) = arg.dirfd {
                    // Validate FD argument.
                    //
                    // Note about EMPTY_PATH:
                    // 1. execveat(fd, "", NULL, NULL, AT_EMPTY_PATH)
                    // 2. openat(fd, "", O_TMPFILE|O_RDWR, 0)
                    // In the first case AT_FDCWD is invalid,
                    // but in the second case AT_FDCWD is valid.
                    to_valid_fd(args[idx])?
                } else {
                    libc::AT_FDCWD
                };
                let is_dot = !empty_path;

                // SAFETY: The ends_with_dot check above
                // ensures we return ENOTDIR when e.g. path is
                // a dot and the file descriptor argument is a
                // regular file. This happens because in this
                // case, joining the directory with an empty
                // path on the next branch essentially adds a
                // trailing slash to the path, making the
                // system call emulator fail with ENOTDIR if
                // the argument is not a directory. This way,
                // we avoid stat'ing the path here to
                // determine whether it's a directory or not.
                if let Some(request) = request {
                    if dirfd == libc::AT_FDCWD {
                        let path = CanonicalPath::new_fd(libc::AT_FDCWD.into(), self.pid)?;

                        // Validate request after procfs(5) read.
                        if !request.is_valid() {
                            return Err(Errno::ESRCH);
                        }

                        path
                    } else {
                        // SAFETY: Get the file descriptor before access check
                        // as it may change after which is a TOCTOU vector.
                        let fd = request.get_fd(dirfd)?;

                        let path = CanonicalPath::new_fd(fd.into(), self.pid)?;

                        if is_dot && path.typ != Some(FileType::Dir) {
                            // FD-only call, no need to delay ENOTDIR.
                            return Err(Errno::ENOTDIR);
                        }

                        path
                    }
                } else if dirfd == libc::AT_FDCWD {
                    CanonicalPath::new_fd(libc::AT_FDCWD.into(), self.pid)?
                } else {
                    // SAFETY: Get the file descriptor before access check
                    // as it may change after which is a TOCTOU vector.
                    let pid_fd = pidfd_open(self.pid, PIDFD_THREAD)?;
                    let fd = pidfd_getfd(pid_fd, dirfd)?;

                    let path = CanonicalPath::new_fd(fd.into(), self.pid)?;

                    if is_dot && path.typ != Some(FileType::Dir) {
                        // FD-only call, no need to delay ENOTDIR.
                        return Err(Errno::ENOTDIR);
                    }

                    path
                }
            } else {
                let fd = if let Some(idx) = arg.dirfd {
                    // Using a bad directory is okay for absolute paths.
                    if path.is_absolute() {
                        None
                    } else {
                        Some(to_valid_fd(args[idx])?)
                    }
                } else {
                    None
                };

                let path =
                    safe_canonicalize(self.pid, fd, &path, arg.fsflags, Some(sandbox.deref()))?;

                // Validate request after canonicalize which may
                // have involved a procfs(5) read.
                if request.map(|req| !req.is_valid()).unwrap_or(false) {
                    return Err(Errno::ESRCH);
                }

                path
            }
        } else {
            // SAFETY: SysArg.path is None asserting dirfd is Some.
            #[expect(clippy::disallowed_methods)]
            let idx = arg.dirfd.unwrap();

            // Validate file descriptor.
            //
            // AT_FDCWD is an invalid file descriptor with NULL path.
            let remote_fd = RawFd::try_from(args[idx]).or(Err(Errno::EBADF))?;
            if remote_fd < 0 {
                // Negative file descriptors are invalid with NULL path.
                return Err(Errno::EBADF);
            }

            if let Some(request) = request {
                // SAFETY: Get the file descriptor before access check
                // as it may change after which is a TOCTOU vector.
                let fd = request.get_fd(remote_fd)?;

                // Validate WANT_READ against O_PATH.
                if arg.fsflags.want_read() && fd_status_flags(&fd)?.contains(OFlag::O_PATH) {
                    return Err(Errno::EBADF);
                }

                CanonicalPath::new_fd(fd.into(), self.pid)?
            } else {
                // SAFETY: Get the file descriptor before access check
                // as it may change after which is a TOCTOU vector.
                let pid_fd = pidfd_open(self.pid, PIDFD_THREAD)?;
                let fd = pidfd_getfd(pid_fd, remote_fd)?;

                // Validate WANT_READ against O_PATH.
                if arg.fsflags.want_read() && fd_status_flags(&fd)?.contains(OFlag::O_PATH) {
                    return Err(Errno::EBADF);
                }

                CanonicalPath::new_fd(fd.into(), self.pid)?
            }
        };

        if !magic && arg.path.is_some() {
            // SAFETY: Deny access to critical and/or suspicious paths.
            canonical_path.abs().check(
                self.pid,
                canonical_path.typ.as_ref(),
                None,
                !sandbox.flags.allow_unsafe_filename(),
                !sandbox.flags.allow_unsafe_mkbdev(),
            )?;
        }

        Ok((canonical_path, magic, doterr, empty_path))
    }

    /// Read data from remote process's memory with `process_vm_readv()`.
    ///
    /// # Safety
    ///
    /// This function is unsafe because the request is not validated.
    pub(crate) unsafe fn read_mem(
        &self,
        local_buffer: &mut [u8],
        remote_addr: u64,
    ) -> Result<usize, Errno> {
        static FORCE_PROC: LazyLock<bool> =
            LazyLock::new(|| std::env::var_os(ENV_NO_CROSS_MEMORY_ATTACH).is_some());
        // SAFETY: Falling back to proc_pid_mem(5) is insecure,
        // and is no longer the default as of 3.32.6.
        static PROC_MEM_F: LazyLock<bool> =
            LazyLock::new(|| std::env::var_os(ENV_PROC_PID_MEM_FALLBACK).is_some());
        if *FORCE_PROC || (*PROC_MEM_F && !*HAVE_CROSS_MEMORY_ATTACH) {
            return self.read_mem_proc(local_buffer, remote_addr);
        }

        // SAFETY: Check pointer against mmap_min_addr.
        if remote_addr < *MMAP_MIN_ADDR {
            return Err(Errno::EFAULT);
        }

        let len = local_buffer.len();
        process_vm_readv(
            self.pid,
            &mut [IoSliceMut::new(local_buffer)],
            &[RemoteIoVec {
                len,
                base: usize::try_from(remote_addr).or(Err(Errno::EFAULT))?,
            }],
        )
    }

    /// Fallback method to read data from `/proc/$pid/mem` when `process_vm_readv()` is unavailable.
    ///
    /// # Safety
    ///
    /// This function is unsafe because the request is not validated.
    pub(crate) unsafe fn read_mem_proc(
        &self,
        local_buffer: &mut [u8],
        remote_addr: u64,
    ) -> Result<usize, Errno> {
        // SAFETY: Check pointer against mmap_min_addr.
        if remote_addr < *MMAP_MIN_ADDR {
            return Err(Errno::EFAULT);
        }

        let mut path = XPathBuf::from_pid(self.pid);
        path.push(b"mem");

        let mut file = safe_open_msym(PROC_FILE(), &path, OFlag::O_RDONLY, ResolveFlag::empty())
            .map(File::from)
            .or(Err(Errno::EACCES))?;
        file.seek(SeekFrom::Start(remote_addr))
            .or(Err(Errno::EACCES))?;

        let mut nread = 0;
        #[expect(clippy::arithmetic_side_effects)]
        while nread < local_buffer.len() {
            match file.read(&mut local_buffer[nread..]) {
                Ok(0) => return Err(Errno::EACCES),
                Ok(n) => nread += n,
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(_) => return Err(Errno::EACCES),
            }
        }

        Ok(nread)
    }

    /// Write data to remote process's memory with `process_vm_writev()`.
    ///
    /// # Safety
    ///
    /// This function is unsafe because the request is not validated.
    pub(crate) unsafe fn write_mem(
        &self,
        local_buffer: &[u8],
        remote_addr: u64,
    ) -> Result<usize, Errno> {
        static FORCE_PROC: LazyLock<bool> =
            LazyLock::new(|| std::env::var_os(ENV_NO_CROSS_MEMORY_ATTACH).is_some());
        // SAFETY: Falling back to proc_pid_mem(5) is insecure,
        // and is no longer the default as of 3.32.6.
        static PROC_MEM_F: LazyLock<bool> =
            LazyLock::new(|| std::env::var_os(ENV_PROC_PID_MEM_FALLBACK).is_some());
        if *FORCE_PROC || (*PROC_MEM_F && !*HAVE_CROSS_MEMORY_ATTACH) {
            return self.write_mem_proc(local_buffer, remote_addr);
        }

        // SAFETY: Check pointer against mmap_min_addr.
        if remote_addr < *MMAP_MIN_ADDR {
            return Err(Errno::EFAULT);
        }

        let len = local_buffer.len();
        if len == 0 {
            return Ok(0);
        }
        process_vm_writev(
            self.pid,
            &[IoSlice::new(local_buffer)],
            &[RemoteIoVec {
                len,
                base: usize::try_from(remote_addr).or(Err(Errno::EFAULT))?,
            }],
        )
    }

    /// Fallback method to write data to `/proc/$pid/mem` when `process_vm_writev()` is unavailable.
    ///
    /// # Safety
    ///
    /// This function is unsafe because the request is not validated.
    pub(crate) unsafe fn write_mem_proc(
        &self,
        local_buffer: &[u8],
        remote_addr: u64,
    ) -> Result<usize, Errno> {
        // SAFETY: Check pointer against mmap_min_addr.
        if remote_addr < *MMAP_MIN_ADDR {
            return Err(Errno::EFAULT);
        } else if local_buffer.is_empty() {
            return Ok(0);
        }

        let mut path = XPathBuf::from_pid(self.pid);
        path.push(b"mem");

        let mut file = safe_open_msym(PROC_FILE(), &path, OFlag::O_WRONLY, ResolveFlag::empty())
            .map(File::from)
            .or(Err(Errno::EACCES))?;
        file.seek(SeekFrom::Start(remote_addr))
            .or(Err(Errno::EACCES))?;

        let mut nwritten = 0;
        #[expect(clippy::arithmetic_side_effects)]
        while nwritten < local_buffer.len() {
            match file.write(&local_buffer[nwritten..]) {
                Ok(0) => return Err(Errno::EACCES),
                Ok(n) => nwritten += n,
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(_) => return Err(Errno::EACCES),
            }
        }

        Ok(nwritten)
    }

    /// Read the path from memory of the process with the given `Pid` with the given address.
    ///
    /// If `request` is `Some()` request is validated after
    /// actions that require validation such as proc reads
    /// and fd transfers. Otherwise, the caller must validate
    /// to verify the path read from sandbox process memory
    /// is what's expected.
    pub(crate) fn remote_path(
        &self,
        addr: u64,
        request: Option<&UNotifyEventRequest>,
    ) -> Result<XPathBuf, Errno> {
        // Initialize path on the heap,
        // bail out if memory allocation fails.
        let mut buf = Vec::new();
        buf.try_reserve(PATH_MIN).or(Err(Errno::ENOMEM))?;

        // Read from process memory.
        // We read PATH_MIN bytes at a time,
        // because most paths are short.
        let mut off = 0;
        #[expect(clippy::arithmetic_side_effects)]
        while off < PATH_MAX {
            // Ensure we have enough space for the next read.
            let len = PATH_MIN.min(PATH_MAX - off);

            if buf.len() < off + len {
                // Extend the buffer to the required size,
                // bail out if memory allocation fails.
                buf.try_reserve(len).or(Err(Errno::ENOMEM))?;
                buf.resize(off + len, 0);
            }

            let ptr = &mut buf[off..off + len];

            // Read remote memory.
            // SAFETY:
            // 1. Assume error on zero-read.
            // 2. Validate the request after memory read.
            let len = unsafe { self.read_mem(ptr, addr + off as u64) }?;
            if len == 0 {
                return Err(Errno::EFAULT);
            } else if request.map(|req| !req.is_valid()).unwrap_or(false) {
                return Err(Errno::ESRCH);
            }

            // Check for NUL-byte.
            if let Some(nul) = memchr::memchr(0, &ptr[..len]) {
                // Adjust to actual size up to NUL-byte.
                off += nul;
                buf.truncate(off);
                buf.shrink_to_fit();
                return Ok(buf.into());
            }

            off += len;
        }

        Err(Errno::ENAMETOOLONG)
    }
}

/// `UNotifyEventRequest` is the type of parameter that user's function
/// would get.
pub(crate) struct UNotifyEventRequest {
    pub(crate) scmpreq: ScmpNotifReq,
    pub(crate) syscall: Sydcall,
    notify_fd: RawFd,
    pub(crate) cache: Arc<WorkerCache<'static>>,
    sandbox: Arc<RwLock<Sandbox>>,
    pub(crate) crypt_map: Option<AesLock>,
    pub(crate) unix_map: UnixMap,
}

impl Serialize for UNotifyEventRequest {
    #[expect(clippy::cognitive_complexity)]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(Some(8))?;

        map.serialize_entry("pid", &self.scmpreq.pid)?;
        map.serialize_entry("sys", &self.syscall)?;
        map.serialize_entry("args", &self.scmpreq.data.args)?;
        map.serialize_entry("arch", &SydArch(self.scmpreq.data.arch))?;

        #[expect(clippy::cast_possible_wrap)]
        let pid = Pid::from_raw(self.scmpreq.pid as libc::pid_t);

        if let Ok(status) = proc_status(pid) {
            map.serialize_entry("cmd", &status.command)?;
            map.serialize_entry("tgid", &status.pid)?;
            map.serialize_entry("sig_caught", &status.sig_caught)?;
            map.serialize_entry("sig_blocked", &status.sig_blocked)?;
            map.serialize_entry("sig_ignored", &status.sig_ignored)?;
            map.serialize_entry("sig_pending_thread", &status.sig_pending_thread)?;
            map.serialize_entry("sig_pending_process", &status.sig_pending_process)?;
            map.serialize_entry("umask", &status.umask)?;
        }

        #[expect(clippy::unnecessary_cast)]
        if let Ok(auxv) = proc_auxv(pid) {
            // Note: libc::AT_* constant are u32 on 32-bit...

            // Base and entry addresses
            if let Some(val) = auxv.get(&(libc::AT_BASE as u64)) {
                map.serialize_entry("at_base", val)?;
            }
            if let Some(val) = auxv.get(&(libc::AT_ENTRY as u64)) {
                map.serialize_entry("at_entry", val)?;
            }

            // Program headers
            if let Some(val) = auxv.get(&(libc::AT_PHDR as u64)) {
                map.serialize_entry("at_phdr", val)?;
            }
            if let Some(val) = auxv.get(&(libc::AT_PHENT as u64)) {
                map.serialize_entry("at_phent", val)?;
            }
            if let Some(val) = auxv.get(&(libc::AT_PHNUM as u64)) {
                map.serialize_entry("at_phnum", val)?;
            }

            // Read AT_RANDOM bytes which is 16 bytes of
            // random data placed by the kernel at the
            // specified address.
            if let Some(addr) = auxv.get(&(libc::AT_RANDOM as u64)) {
                let mut at_random = [0u8; 16];
                if *addr >= *MMAP_MIN_ADDR && self.read_mem(&mut at_random, *addr).is_ok() {
                    map.serialize_entry("at_random", &HEXLOWER.encode(&at_random))?;
                }
            }

            // AT_SECURE: we set this ourselves
            // unless trace/allow_unsafe_exec_libc:1 is passed at startup,
            // however when we set it, the value will still incorrectly
            // show as false because this file is not updated after
            // process startup.
            if let Some(val) = auxv.get(&(libc::AT_SECURE as u64)) {
                let sandbox = self.sandbox.read().unwrap_or_else(|err| err.into_inner());
                let seclibc = !sandbox.flags.allow_unsafe_exec_libc();
                drop(sandbox); // release the read-lock.

                if seclibc {
                    map.serialize_entry("at_secure", &true)?;
                } else {
                    map.serialize_entry("at_secure", &(*val != 0))?;
                }
            }
        }

        let sp = proc_stack_pointer(pid)
            .map(|sp| (sp & !0xF).saturating_sub(16))
            .ok();
        map.serialize_entry("sp", &sp)?;

        let ip = self.scmpreq.data.instr_pointer;
        map.serialize_entry("ip", &ip)?;

        let mut ip_mem = [0u8; 64];
        let mut sp_mem = [0u8; 64];
        let mut ip_read = false;
        let mut sp_read = false;

        if ip >= *MMAP_MIN_ADDR && self.read_mem(&mut ip_mem, ip).is_ok() {
            ip_read = true;
        }

        if let Some(sp) = sp {
            if sp >= *MMAP_MIN_ADDR && self.read_mem(&mut sp_mem, sp).is_ok() {
                sp_read = true;
            }
        }

        map.serialize_entry(
            "sp_mem",
            &if sp_read {
                Some(HEXLOWER.encode(&sp_mem))
            } else {
                None
            },
        )?;

        map.serialize_entry(
            "ip_mem",
            &if ip_read {
                Some(HEXLOWER.encode(&ip_mem))
            } else {
                None
            },
        )?;

        map.serialize_entry("maps", &proc_maps(pid).ok())?;

        map.end()
    }
}

impl UNotifyEventRequest {
    pub(crate) fn new(
        scmpreq: ScmpNotifReq,
        syscall: Sydcall,
        notify_fd: RawFd,
        cache: Arc<WorkerCache<'static>>,
        sandbox: Arc<RwLock<Sandbox>>,
        crypt_map: Option<AesLock>,
        unix_map: UnixMap,
    ) -> Self {
        UNotifyEventRequest {
            scmpreq,
            syscall,
            notify_fd,
            cache,
            sandbox,
            crypt_map,
            unix_map,
        }
    }

    /// Get a read lock to the sandbox.
    pub(crate) fn get_sandbox(&self) -> SandboxGuard<'_> {
        // Note, if another user of this mutex panicked while holding
        // the mutex, then this call will return an error once the mutex
        // is acquired. We ignore this case here and fall through
        // because Syd emulator threads are free to panic independent of
        // each other.
        SandboxGuard::Read(self.sandbox.read().unwrap_or_else(|err| err.into_inner()))
    }

    /// Get a write lock to the sandbox.
    pub(crate) fn get_mut_sandbox(&self) -> SandboxGuard<'_> {
        // Note, if another user of this mutex panicked while holding
        // the mutex, then this call will return an error once the mutex
        // is acquired. We ignore this case here and fall through
        // because Syd emulator threads are free to panic independent of
        // each other.
        SandboxGuard::Write(self.sandbox.write().unwrap_or_else(|err| err.into_inner()))
    }

    /// Check SCM_RIGHTS file types at sendm{,m}sg(2), recv{,m}msg{,_time64}(2) boundaries.
    pub(crate) fn check_scm_rights<Fd: AsFd>(
        &self,
        fd: Fd,
        flags: Flags,
        op: u8,
        verbose: bool,
    ) -> Result<(), Errno> {
        // SAFETY: Deny sending/receiving file descriptors referring to
        // 1. Directories (pledge does the same).
        // 2. Block devices unless trace/allow_unsafe_mkbdev:1 is set.
        // 3. Symbolic links unless trace/allow_unsafe_symlinks:1 is set.
        //
        // Note, we do allow files of unknown type such as epoll
        // fds and event fds as some programs such as pipewire
        // depend on this. See test-pw-filter test of pipewire
        // for more information about this.
        let ftyp = file_type(fd, None, false)?;
        let emsg = match ftyp {
            FileType::Dir => "report a bug!",
            FileType::Blk if !flags.allow_unsafe_mkbdev() => "use `trace/allow_unsafe_mkbdev:1'",
            FileType::Lnk if !flags.allow_unsafe_symlinks() => {
                "use `trace/allow_unsafe_symlinks:1'"
            }
            _ => return Ok(()),
        };

        if verbose {
            error!("ctx": "trusted_scm_rights", "sys": op2name(op),
                "msg": format!("SCM_RIGHTS for unsafe file type `{ftyp:?}' blocked"),
                "tip": emsg, "req": &self);
        } else {
            error!("ctx": "trusted_scm_rights", "sys": op2name(op),
                "msg": format!("SCM_RIGHTS for unsafe file type `{ftyp:?}' blocked"),
                "tip": emsg, "pid": self.scmpreq.pid);
        }

        Err(Errno::EACCES)
    }

    /// Find a bind address by parent and base names.
    ///
    /// Used for informational purposes at recvfrom(2) boundary.
    pub(crate) fn find_unix_addr(&self, base: &XPath) -> Result<UnixAddr, Errno> {
        self.clr_unix()?; // cleanup bind-map from unused inodes.
        let unix_map = self.unix_map.read().unwrap_or_else(|err| err.into_inner());
        for unix_val in unix_map.values() {
            if let Some(addr) = unix_val.addr {
                if let Some(path) = addr.path() {
                    let path = XPath::from_bytes(path.as_os_str().as_bytes());
                    if base.is_equal(path.split().1.as_bytes()) {
                        return Ok(addr);
                    }
                }
            }
        }

        Err(Errno::ENOENT)
    }

    /// Add a bind address to the UnixMap. This has been split from the sandbox policy
    /// as of version 3.33.1 because it has no bearing on access rights and is provided
    /// for convenience for getpeername(2), getsockname(2), recvfrom(2), and recvmsg(2).
    ///
    /// This function is called for bind(2) and connect(2).
    pub(crate) fn add_unix<Fd: AsFd>(
        &self,
        fd: Fd,
        tid: Pid,
        addr: Option<&UnixAddr>,
        peer: Option<&UnixAddr>,
    ) -> Result<(), Errno> {
        // Get socket inode.
        let inode = fstatx(fd, STATX_INO).map(|statx| statx.stx_ino)?;

        // Get process id.
        let pid = proc_tgid(tid)?;

        // Record/merge unix address.
        let mut unix_map = self.unix_map.write().unwrap_or_else(|err| err.into_inner());
        match unix_map.entry(inode) {
            Entry::Occupied(mut entry) => {
                let entry = entry.get_mut();
                entry.pid = pid;
                if let Some(addr) = addr {
                    entry.addr = Some(*addr);
                }
                if let Some(peer) = peer {
                    entry.peer = Some(*peer);
                }
            }
            Entry::Vacant(entry) => {
                entry.insert(UnixVal {
                    pid,
                    addr: addr.copied(),
                    peer: peer.copied(),
                });
            }
        }
        let unix_len = unix_map.len();

        // SAFETY: Do _not_ hold a write lock during /proc read.
        drop(unix_map);

        // Cleanup unix map from unused inodes as necessary.
        if unix_len > 128 {
            self.clr_unix()?;
        }

        Ok(())
    }

    // Cleanup unix map from unused inodes.
    pub(crate) fn clr_unix(&self) -> Result<(), Errno> {
        // Try netlink(7) first, fallback to proc_net(5).
        // netlink(7) requires CONFIG_UNIX_DIAG enabled.
        let inodes = unix_inodes().or_else(|_| proc_unix_inodes(self.scmpreq.pid()))?;
        let mut unix_map = self.unix_map.write().unwrap_or_else(|err| err.into_inner());
        unix_map.retain(|inode, _| inodes.contains(inode));
        Ok(())
    }

    pub(crate) fn get_unix(&self, inode: u64) -> Option<UnixVal> {
        self.unix_map
            .read()
            .unwrap_or_else(|err| err.into_inner())
            .get(&inode)
            .copied()
    }

    /// Read an xattr name from the given address.
    ///
    /// Name must be a NUL-terminated string or `Err(Errno::ERANGE)` is returned.
    pub(crate) fn read_xattr(&self, addr: u64) -> Result<CString, Errno> {
        let mut buf = Vec::new();

        buf.try_reserve(XATTR_NAME_MAX).or(Err(Errno::ENOMEM))?;
        buf.resize(XATTR_NAME_MAX, 0);

        let mut n = self.read_mem(&mut buf, addr)?;

        let z = memchr(0, &buf[..n]).ok_or(Errno::ERANGE)?;
        n = n.min(z.checked_add(1).ok_or(Errno::ERANGE)?);
        buf.truncate(n);

        // Check for empty name.
        let len = buf.len(); // Includes NUL-byte.
        if len <= 1 {
            return Err(Errno::ERANGE);
        }

        // Check for qualified name in namespace.attribute form.
        // EINVAL here is expected by sys-apps/attr's tests.
        match memchr(b'.', &buf) {
            None => Err(Errno::EOPNOTSUPP),
            Some(0) => Err(Errno::EINVAL),
            Some(n) if n >= len.saturating_sub(2) => Err(Errno::EINVAL),
            Some(_) => {
                // Release excess memory.
                buf.shrink_to_fit();
                // SAFETY:
                // 1. `buf` has one nul-byte as its last element.
                // 2. `buf` does not have any interior nul-bytes.
                Ok(unsafe { CString::from_vec_with_nul_unchecked(buf) })
            }
        }
    }

    /// Read the sa_flags member of `struct sigaction` from the given address.
    pub(crate) fn read_sa_flags(&self, addr: u64) -> Result<SaFlags, Errno> {
        let req = self.scmpreq;

        // Determine the target word size. (4 for 32-bit, 8 for 64-bit).
        let is32 = scmp_arch_bits(req.data.arch) == 32;
        let word_size = if is32 { 4usize } else { 8usize };

        // Offset of sa_flags within struct sigaction.
        let offset = word_size as u64; // 4 on 32-bit, 8 on 64-bit.

        // Compute absolute read address, checking for overflow.
        let read_addr = addr.checked_add(offset).ok_or(Errno::EFAULT)?;

        // Initialize vector on stack.
        //
        // Buffer up to 8 bytes; will only use first `word_size` bytes.
        let mut buf = [0u8; 8];

        // Read from process memory.
        //
        // Loop until we've read `word_size` bytes,
        // or encounter EOF (zero-read).
        let process = RemoteProcess::new(self.scmpreq.pid());
        let mut nread = 0;
        while nread < word_size {
            // Adjust current slice.
            //
            // Compute absolute read address plus the offset, checking for overflow.
            let slice = &mut buf[nread..word_size];
            let read_addr = read_addr.checked_add(nread as u64).ok_or(Errno::EFAULT)?;

            // Read remote memory.
            //
            // SAFETY: The request is going to be validated.
            let n = unsafe { process.read_mem(slice, read_addr) }?;

            // SAFETY: Assume error on zero-read.
            if n == 0 {
                return Err(Errno::EFAULT);
            }

            // Compute next offset, check for overflow.
            nread = nread.checked_add(n).ok_or(Errno::EFAULT)?;
        }

        // SAFETY: Check request validity after memory read.
        if !self.is_valid() {
            return Err(Errno::ESRCH);
        }

        // Interpret raw bytes in native endianness.
        #[expect(clippy::cast_possible_truncation)]
        #[expect(clippy::cast_possible_wrap)]
        #[expect(clippy::disallowed_methods)]
        let raw = if word_size == 8 {
            u64::from_ne_bytes(buf) as libc::c_int
        } else {
            // SAFETY: `word_size` must always be 4 here.
            u32::from_ne_bytes(buf[..4].try_into().unwrap()) as libc::c_int
        };

        Ok(SaFlags::from_bits_truncate(raw))
    }

    /// Read the `libc::open_how` struct from process memory
    /// at the given address and size.
    pub(crate) fn remote_ohow(&self, addr: u64, size: u64) -> Result<libc::open_how, Errno> {
        const OPEN_HOW_SIZE: usize = std::mem::size_of::<libc::open_how>();
        const OPEN_HOW_ALIGN: usize = std::mem::align_of::<libc::open_how>();

        // SAFETY: Validate size argument.
        let size = usize::try_from(size).or(Err(Errno::EINVAL))?;
        match size.cmp(&OPEN_HOW_SIZE) {
            Ordering::Equal => {}
            Ordering::Less => return Err(Errno::EINVAL),
            Ordering::Greater if size % OPEN_HOW_ALIGN == 0 => return Err(Errno::E2BIG),
            Ordering::Greater => return Err(Errno::EFAULT),
        };

        // SAFETY: Validate address argument.
        if addr < *MMAP_MIN_ADDR {
            return Err(Errno::EFAULT);
        }

        let mut buf = [0u8; OPEN_HOW_SIZE];
        self.read_mem(&mut buf, addr)?;

        // SAFETY: The following unsafe block assumes that:
        // 1. The memory layout of open_how in our Rust environment
        //    matches that of the target process.
        // 2. The request.process.read_mem call has populated buf with valid data
        //    of the appropriate size (ensured by the size check above).
        // 3. The buffer is appropriately aligned for reading an
        //    open_how struct. If the remote process's representation of
        //    open_how was correctly aligned, our local buffer should be
        //    too, since it's an array on the stack.
        Ok(unsafe { std::ptr::read_unaligned(buf.as_ptr() as *const _) })
    }

    /// Read the `libc::utimbuf` struct from process memory at the given address.
    /// Convert it to a `libc::timespec[2]` for easy interoperability.
    pub(crate) fn remote_utimbuf(&self, addr: u64) -> Result<(TimeSpec, TimeSpec), Errno> {
        if addr == 0 {
            // utimbuf pointer is NULL: Set to current time.
            return Ok((TimeSpec::UTIME_NOW, TimeSpec::UTIME_NOW));
        } else if addr < *MMAP_MIN_ADDR {
            // utimbuf pointer is invalid: return EFAULT.
            return Err(Errno::EFAULT);
        }

        let mut buf = [0u8; std::mem::size_of::<libc::utimbuf>()];
        self.read_mem(&mut buf, addr)?;

        // SAFETY: The following unsafe block assumes that:
        // 1. The memory layout of utimbuf in our Rust environment
        //    matches that of the target process.
        // 2. The request.process.read_mem call has populated buf with valid data
        //    of the appropriate size (ensured by the size check above).
        // 3. The buffer is appropriately aligned for reading a utimbuf
        //    struct. If the remote process's representation of utimbuf
        //    was correctly aligned, our local buffer should be too,
        //    since it's an array on the stack.
        let utimbuf: libc::utimbuf = unsafe { std::ptr::read_unaligned(buf.as_ptr() as *const _) };

        Ok((
            TimeSpec::new(utimbuf.actime, 0),
            TimeSpec::new(utimbuf.modtime, 0),
        ))
    }

    /// Read the `libc::timeval[2]` struct from process memory at the given address.
    /// Convert it to a `libc::timespec[2]` for easy interoperability.
    pub(crate) fn remote_timeval(&self, addr: u64) -> Result<(TimeSpec, TimeSpec), Errno> {
        if addr == 0 {
            // timeval pointer is NULL: Set to current time.
            return Ok((TimeSpec::UTIME_NOW, TimeSpec::UTIME_NOW));
        } else if addr < *MMAP_MIN_ADDR {
            // timeval pointer is invalid: return EFAULT.
            return Err(Errno::EFAULT);
        }

        let mut buf = [0u8; std::mem::size_of::<libc::timeval>() * 2];
        self.read_mem(&mut buf, addr)?;

        // SAFETY: The following unsafe block assumes that:
        // 1. The memory layout of timeval in our Rust environment
        //    matches that of the target process.
        // 2. The request.process.read_mem call has populated buf with valid data
        //    of the appropriate size (ensured by the size check above).
        // 3. The buffer is appropriately aligned for reading a timeval
        //    struct. If the remote process's representation of timeval
        //    was correctly aligned, our local buffer should be too,
        //    since it's an array on the stack.
        #[expect(clippy::cast_ptr_alignment)]
        let timevals = unsafe {
            // Create a raw pointer to the buffer.
            let ptr = buf.as_ptr() as *const libc::timeval;

            // Read the timeval values from the buffer.
            [
                std::ptr::read_unaligned(ptr),
                std::ptr::read_unaligned(ptr.add(1)),
            ]
        };

        Ok((
            TimeSpec::new(
                timevals[0].tv_sec,
                (timevals[0].tv_usec as timespec_tv_nsec_t).saturating_mul(1_000), /* ms->ns */
            ),
            TimeSpec::new(
                timevals[1].tv_sec,
                (timevals[1].tv_usec as timespec_tv_nsec_t).saturating_mul(1_000), /* ms->ns */
            ),
        ))
    }

    /// Read the `TimeSpec32` struct from process memory at the given address.
    pub(crate) fn remote_timespec32(&self, addr: u64) -> Result<TimeSpec, Errno> {
        if addr < *MMAP_MIN_ADDR {
            // timespec pointer is invalid: return EFAULT.
            return Err(Errno::EFAULT);
        }

        let mut buf = [0u8; std::mem::size_of::<TimeSpec32>()];
        self.read_mem(&mut buf, addr)?;

        // SAFETY: The following unsafe block assumes that:
        // 1. The memory layout of timespec in our Rust environment
        //    matches that of the target process.
        // 2. The request.process.read_mem call has populated buf with valid data
        //    of the appropriate size (ensured by the size check above).
        // 3. The buffer is appropriately aligned for reading a timespec
        //    struct. If the remote process's representation of timespec
        //    was correctly aligned, our local buffer should be too,
        //    since it's an array on the stack.
        #[expect(clippy::cast_ptr_alignment)]
        let timespec = unsafe {
            // Create a raw pointer to the buffer.
            let ptr = buf.as_ptr() as *const TimeSpec32;

            // Read the timespec values from the buffer.
            std::ptr::read_unaligned(ptr)
        };

        Ok(TimeSpec::new(
            timespec.tv_sec.into(),
            timespec.tv_nsec.into(),
        ))
    }

    /// Read the `TimeSpec64[2]` struct from process memory at the given address.
    // `as _` casts are used to write portable code for x32 and i386.
    #[expect(clippy::as_underscore)]
    pub(crate) fn remote_timespec64(&self, addr: u64) -> Result<TimeSpec, Errno> {
        if addr < *MMAP_MIN_ADDR {
            // timespec pointer is invalid: return EFAULT.
            return Err(Errno::EFAULT);
        }

        let mut buf = [0u8; std::mem::size_of::<TimeSpec64>()];
        self.read_mem(&mut buf, addr)?;

        // SAFETY: The following unsafe block assumes that:
        // 1. The memory layout of timespec in our Rust environment
        //    matches that of the target process.
        // 2. The request.process.read_mem call has populated buf with valid data
        //    of the appropriate size (ensured by the size check above).
        // 3. The buffer is appropriately aligned for reading a timespec
        //    struct. If the remote process's representation of timespec
        //    was correctly aligned, our local buffer should be too,
        //    since it's an array on the stack.
        #[expect(clippy::cast_ptr_alignment)]
        let timespec = unsafe {
            // Create a raw pointer to the buffer.
            let ptr = buf.as_ptr() as *const TimeSpec64;

            // Read the timespec values from the buffer.
            std::ptr::read_unaligned(ptr)
        };

        Ok(TimeSpec::new(timespec.tv_sec as _, timespec.tv_nsec as _))
    }

    /// Read the `TimeSpec32[2]` struct from process memory at the given address.
    pub(crate) fn remote_timespec32_2(&self, addr: u64) -> Result<(TimeSpec, TimeSpec), Errno> {
        if addr == 0 {
            // timespec pointer is NULL: Set to current time.
            return Ok((TimeSpec::UTIME_NOW, TimeSpec::UTIME_NOW));
        } else if addr < *MMAP_MIN_ADDR {
            // timespec pointer is invalid: return EFAULT.
            return Err(Errno::EFAULT);
        }

        let mut buf = [0u8; std::mem::size_of::<TimeSpec32>() * 2];
        self.read_mem(&mut buf, addr)?;

        // SAFETY: The following unsafe block assumes that:
        // 1. The memory layout of timespec in our Rust environment
        //    matches that of the target process.
        // 2. The request.process.read_mem call has populated buf with valid data
        //    of the appropriate size (ensured by the size check above).
        // 3. The buffer is appropriately aligned for reading a timespec
        //    struct. If the remote process's representation of timespec
        //    was correctly aligned, our local buffer should be too,
        //    since it's an array on the stack.
        #[expect(clippy::cast_ptr_alignment)]
        let timespecs = unsafe {
            // Create a raw pointer to the buffer.
            let ptr = buf.as_ptr() as *const TimeSpec32;

            // Read the timespec values from the buffer.
            [
                std::ptr::read_unaligned(ptr),
                std::ptr::read_unaligned(ptr.add(1)),
            ]
        };

        Ok((
            TimeSpec::new(timespecs[0].tv_sec.into(), timespecs[0].tv_nsec.into()),
            TimeSpec::new(timespecs[1].tv_sec.into(), timespecs[1].tv_nsec.into()),
        ))
    }

    /// Read the `TimeSpec64[2]` struct from process memory at the given address.
    // `as _` casts are used to write portable code for x32 and i386.
    #[expect(clippy::as_underscore)]
    pub(crate) fn remote_timespec64_2(&self, addr: u64) -> Result<(TimeSpec, TimeSpec), Errno> {
        if addr == 0 {
            // timespec pointer is NULL: Set to current time.
            return Ok((TimeSpec::UTIME_NOW, TimeSpec::UTIME_NOW));
        } else if addr < *MMAP_MIN_ADDR {
            // timespec pointer is invalid: return EFAULT.
            return Err(Errno::EFAULT);
        }

        let mut buf = [0u8; std::mem::size_of::<TimeSpec64>() * 2];
        self.read_mem(&mut buf, addr)?;

        // SAFETY: The following unsafe block assumes that:
        // 1. The memory layout of timespec in our Rust environment
        //    matches that of the target process.
        // 2. The request.process.read_mem call has populated buf with valid data
        //    of the appropriate size (ensured by the size check above).
        // 3. The buffer is appropriately aligned for reading a timespec
        //    struct. If the remote process's representation of timespec
        //    was correctly aligned, our local buffer should be too,
        //    since it's an array on the stack.
        #[expect(clippy::cast_ptr_alignment)]
        let timespecs = unsafe {
            // Create a raw pointer to the buffer.
            let ptr = buf.as_ptr() as *const TimeSpec64;

            // Read the timespec values from the buffer.
            [
                std::ptr::read_unaligned(ptr),
                std::ptr::read_unaligned(ptr.add(1)),
            ]
        };

        Ok((
            TimeSpec::new(timespecs[0].tv_sec as _, timespecs[0].tv_nsec as _),
            TimeSpec::new(timespecs[1].tv_sec as _, timespecs[1].tv_nsec as _),
        ))
    }

    /// Read path from the given system call argument with the given request.
    /// Check for magic prefix is magic is true.
    ///
    /// Returns `CanonicalPath` and two booleans is-magic and is-empty-path.
    pub(crate) fn read_path<'b>(
        &self,
        sandbox: &SandboxGuard,
        arg: SysArg,
        magic: bool,
    ) -> Result<(CanonicalPath<'b>, bool, bool), Errno> {
        let process = RemoteProcess::new(self.scmpreq.pid());

        // SAFETY: The request is validated by read_path.
        let (path, magic, doterr, empty_path) =
            process.read_path(sandbox, self.scmpreq.data.args, arg, magic, Some(self))?;

        // Determine FD-only system calls.
        // We return EACCES rather than ENOENT for these.
        let is_fd = empty_path && arg.flags.contains(SysFlags::EMPTY_PATH);

        // (a) Delayed dotlast Errno::ENOENT handler, see above for the rationale.
        // (b) SAFETY: the Missing check is skipped by fs::canonicalize on purpose,
        // so that EEXIST return value cannot be abused to locate hidden paths.
        if !doterr {
            Ok((path, magic, empty_path))
        } else if path
            .typ
            .as_ref()
            .map(|typ| !typ.is_symlink())
            .unwrap_or(false)
        {
            // Path exists and is not a symbolic link.
            // Return EACCES if this is FD-only call.
            // Return ENOENT if either one of path or parent is hidden.
            // Return EEXIST if not.
            if is_fd {
                Err(Errno::EACCES)
            } else if sandbox.is_hidden(path.abs()) || sandbox.is_hidden(path.abs().parent()) {
                Err(Errno::ENOENT)
            } else {
                Err(Errno::EEXIST)
            }
        } else if is_fd {
            Err(Errno::EACCES)
        } else {
            Err(Errno::ENOENT)
        }
    }

    /// Read data from remote process's memory with `process_vm_readv()`.
    pub(crate) fn read_mem(
        &self,
        local_buffer: &mut [u8],
        remote_addr: u64,
    ) -> Result<usize, Errno> {
        let process = RemoteProcess::new(self.scmpreq.pid());

        // SAFETY: The request is validated.
        match unsafe { process.read_mem(local_buffer, remote_addr) } {
            Ok(n) => {
                if self.is_valid() {
                    Ok(n)
                } else {
                    Err(Errno::ESRCH)
                }
            }
            Err(errno) => Err(errno),
        }
    }

    /// Write data to remote process's memory with `process_vm_writev()`.
    #[inline(always)]
    pub(crate) fn write_mem(&self, local_buffer: &[u8], remote_addr: u64) -> Result<usize, Errno> {
        if local_buffer.is_empty() {
            return Ok(0);
        }
        let process = RemoteProcess::new(self.scmpreq.pid());

        // SAFETY: The request is validated.
        match unsafe { process.write_mem(local_buffer, remote_addr) } {
            Ok(n) => {
                if self.is_valid() {
                    Ok(n)
                } else {
                    Err(Errno::ESRCH)
                }
            }
            Err(errno) => Err(errno),
        }
    }

    /// Get file descriptor from remote process with pidfd_getfd(2).
    ///
    /// This function requires Linux 5.6+.
    pub(crate) fn get_fd(&self, remote_fd: RawFd) -> Result<OwnedFd, Errno> {
        // SAFETY: Check if the RawFd is valid.
        if remote_fd < 0 {
            return Err(Errno::EBADF);
        }

        // Open a PidFd or use an already opened one.
        let pid_fd = self.pidfd_open()?;

        // Transfer fd using pidfd_getfd(2)
        pidfd_getfd(pid_fd, remote_fd)
    }

    /// Send a signal to the PIDFd of the process.
    pub(crate) fn pidfd_kill(&self, sig: i32) -> Result<(), Errno> {
        // Open a PidFd by validating it.
        let pid_fd = self.pidfd_open()?;
        pidfd_send_signal(&pid_fd, sig)?;

        // SAFETY: Release memory immediately using process_mrelease(2) if we
        // have sent a SIGKILL to the sandbox process. Above all, this is useful
        // for memory sandboxing.
        if sig == libc::SIGKILL {
            let _ = process_mrelease(&pid_fd);
        }

        Ok(())
    }

    /// Open a PidFd and validate it against the request.
    pub(crate) fn pidfd_open(&self) -> Result<OwnedFd, Errno> {
        // Open the PIDFd.
        let pid_fd = pidfd_open(self.scmpreq.pid(), PIDFD_THREAD)?;

        // SAFETY:
        // 1. Validate the PIDFd by validating the request ID if submitted.
        // 2. EAGAIN|EINTR is handled.
        // 3. ENOENT means child died mid-way.
        if seccomp_notify_id_valid(self.notify_fd, self.scmpreq.id).is_err() {
            return Err(Errno::ESRCH);
        }

        Ok(pid_fd)
    }

    /// Send the request pid a signal based on the given action.
    ///
    /// Non-signaling actions default to SIGKILL.
    pub(crate) fn kill(&self, action: Action) -> Result<(), Errno> {
        self.pidfd_kill(
            action
                .signal()
                .map(|sig| sig as libc::c_int)
                .unwrap_or(libc::SIGKILL),
        )
    }

    /// Let the kernel continue the syscall.
    ///
    /// # Safety
    /// CAUTION! This method is unsafe because it may suffer TOCTOU attack.
    /// Please read `seccomp_unotify(2)` "NOTES/Design goals; use of `SECCOMP_USER_NOTIF_FLAG_CONTINUE`"
    /// before using this method.
    pub(crate) unsafe fn continue_syscall(&self) -> ScmpNotifResp {
        ScmpNotifResp::new(self.scmpreq.id, 0, 0, ScmpNotifRespFlags::CONTINUE.bits())
    }

    /// Returns error to supervised process.
    pub(crate) fn fail_syscall(&self, err: Errno) -> ScmpNotifResp {
        assert!(err != Errno::UnknownErrno);
        #[expect(clippy::arithmetic_side_effects)]
        ScmpNotifResp::new(self.scmpreq.id, 0, -(err as i32), 0)
    }

    /// Returns value to supervised process.
    pub(crate) fn return_syscall(&self, val: i64) -> ScmpNotifResp {
        ScmpNotifResp::new(self.scmpreq.id, val, 0, 0)
    }

    /// Check if this event is still valid.
    /// In some cases this is necessary, please check `seccomp_unotify(2)` for more information.
    #[inline(always)]
    pub(crate) fn is_valid(&self) -> bool {
        // EAGAIN|EINTR is handled.
        // ENOENT means child died mid-way.
        seccomp_notify_id_valid(self.notify_fd, self.scmpreq.id).is_ok()
    }

    /// Add a file descriptor to the supervised process.
    /// This could help avoid TOCTOU attack in some cases.
    pub(crate) fn add_fd<Fd: AsFd>(
        &self,
        src_fd: Fd,
        close_on_exec: bool,
        randomize_fds: bool,
    ) -> Result<RawFd, Errno> {
        #[expect(clippy::cast_possible_truncation)]
        let (newfd, flags) = if randomize_fds {
            (
                proc_rand_fd(self.scmpreq.pid())?,
                libc::SECCOMP_ADDFD_FLAG_SETFD as u32,
            )
        } else {
            (0, 0)
        };

        let newfd_flags = if close_on_exec {
            libc::O_CLOEXEC as u32
        } else {
            0
        };

        #[expect(clippy::cast_sign_loss)]
        let addfd: libc::seccomp_notif_addfd = libc::seccomp_notif_addfd {
            id: self.scmpreq.id,
            srcfd: src_fd.as_fd().as_raw_fd() as u32,
            newfd: newfd as u32,
            flags,
            newfd_flags,
        };

        // EAGAIN|EINTR is retried.
        // Other errors are fatal,
        // including ENOENT which means child died mid-way.
        seccomp_notify_addfd(self.notify_fd, std::ptr::addr_of!(addfd))
    }

    /// Add a file descriptor to the supervised process,
    /// and reply to the seccomp request at the same time.
    /// This could help avoid TOCTOU attack in some cases.
    pub(crate) fn send_fd<Fd: AsFd>(
        &self,
        src_fd: Fd,
        close_on_exec: bool,
        randomize_fds: bool,
    ) -> Result<ScmpNotifResp, Errno> {
        #[expect(clippy::cast_possible_truncation)]
        let (newfd, flags) = if randomize_fds {
            (
                proc_rand_fd(self.scmpreq.pid())?,
                (libc::SECCOMP_ADDFD_FLAG_SEND as u32 | libc::SECCOMP_ADDFD_FLAG_SETFD as u32),
            )
        } else {
            (0, libc::SECCOMP_ADDFD_FLAG_SEND as u32)
        };

        let newfd_flags = if close_on_exec {
            libc::O_CLOEXEC as u32
        } else {
            0
        };

        #[expect(clippy::cast_sign_loss)]
        let addfd: libc::seccomp_notif_addfd = libc::seccomp_notif_addfd {
            id: self.scmpreq.id,
            srcfd: src_fd.as_fd().as_raw_fd() as u32,
            newfd: newfd as u32,
            flags,
            newfd_flags,
        };

        // EAGAIN|EINTR is retried.
        // Other errors are fatal,
        // including ENOENT which means child died mid-way.
        seccomp_notify_addfd(self.notify_fd, std::ptr::addr_of!(addfd))?;

        // We do not need to send a response,
        // send a dummy response to the caller
        // can skip it gracefully.
        Ok(ScmpNotifResp::new(0, 0, EIDRM, 0))
    }
}