sandlock-core 0.4.8

Lightweight process sandbox using Landlock, seccomp-bpf, and seccomp user notification
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
//! Seccomp notification handlers for chroot filesystem interception.
//!
//! Intercepts path-resolving syscalls, rewrites paths via the resolve module,
//! and performs on-behalf operations. Composes with COW when active.

use std::ffi::CString;
use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use tokio::sync::Mutex;

use crate::chroot::resolve::{openat2_in_root, resolve_in_root, to_virtual_path};
use crate::procfs::{build_dirent64, DT_DIR, DT_LNK, DT_REG};
use crate::seccomp::notif::{read_child_mem, write_child_mem, NotifAction, SupervisorState};
use crate::sys::structs::{SeccompNotif, SeccompNotifAddfd, SECCOMP_IOCTL_NOTIF_ADDFD};

// ============================================================
// Chroot policy context
// ============================================================

/// Bundled chroot policy passed to all handlers.
pub(crate) struct ChrootCtx<'a> {
    pub root: &'a Path,
    pub readable: &'a [PathBuf],
    pub writable: &'a [PathBuf],
    pub denied: &'a [PathBuf],
}

impl ChrootCtx<'_> {
    fn is_denied(&self, virtual_path: &Path) -> bool {
        self.denied.iter().any(|p| virtual_path.starts_with(p))
    }

    /// Check if `virtual_path` is allowed for reading.
    /// Also allows access to ancestor directories of readable paths
    /// (e.g. "/" is allowed if "/usr" is readable, since you need to open "/"
    /// to list or traverse to "/usr").
    fn can_read(&self, virtual_path: &Path) -> bool {
        if self.is_denied(virtual_path) {
            return false;
        }
        self.readable.is_empty()
            || self.readable.iter().any(|p| virtual_path.starts_with(p) || p.starts_with(virtual_path))
            || self.writable.iter().any(|p| virtual_path.starts_with(p) || p.starts_with(virtual_path))
    }

    /// Check if `virtual_path` is allowed for writing.
    fn can_write(&self, virtual_path: &Path) -> bool {
        !self.is_denied(virtual_path)
            && self.writable.iter().any(|p| virtual_path.starts_with(p))
    }
}

// ============================================================
// Shared helpers
// ============================================================

/// Read a NUL-terminated path from child memory, page-by-page.
fn read_path(notif: &SeccompNotif, addr: u64, notif_fd: RawFd) -> Option<String> {
    if addr == 0 {
        return None;
    }
    const PAGE_SIZE: u64 = 4096;
    let mut result = Vec::with_capacity(256);
    let mut cur = addr;
    while result.len() < 4096 {
        let page_remaining = PAGE_SIZE - (cur % PAGE_SIZE);
        let to_read = page_remaining.min((4096 - result.len()) as u64) as usize;
        let bytes = read_child_mem(notif_fd, notif.id, notif.pid, cur, to_read).ok()?;
        if let Some(nul) = bytes.iter().position(|&b| b == 0) {
            result.extend_from_slice(&bytes[..nul]);
            return String::from_utf8(result).ok();
        }
        result.extend_from_slice(&bytes);
        cur += to_read as u64;
    }
    String::from_utf8(result).ok()
}

/// Resolve a child path to (host_path, virtual_path) within the chroot.
///
/// Uses `openat2(RESOLVE_IN_ROOT)` for kernel-based symlink resolution,
/// falling back to manual resolution on older kernels.
fn resolve_chroot_path(
    notif: &SeccompNotif,
    dirfd: i64,
    path: &str,
    chroot_root: &Path, // kept as bare Path for internal use
) -> Option<(PathBuf, PathBuf)> {
    let full_path = if Path::new(path).is_absolute() {
        path.to_string()
    } else {
        let dirfd32 = dirfd as i32;
        let base_host = if dirfd32 == libc::AT_FDCWD {
            std::fs::read_link(format!("/proc/{}/cwd", notif.pid)).ok()?
        } else {
            std::fs::read_link(format!("/proc/{}/fd/{}", notif.pid, dirfd)).ok()?
        };
        let base_virtual = to_virtual_path(chroot_root, &base_host)?;
        let combined = base_virtual.join(path);
        combined.to_string_lossy().to_string()
    };
    resolve_in_root(chroot_root, &full_path)
}

/// Convert a Path to CString, returning Errno on failure.
fn path_cstr(path: &Path, err: i32) -> Result<CString, NotifAction> {
    CString::new(path.to_str().unwrap_or("")).map_err(|_| NotifAction::Errno(err))
}

/// Get the errno from the last OS error, with a fallback.
fn last_errno(fallback: i32) -> i32 {
    std::io::Error::last_os_error()
        .raw_os_error()
        .unwrap_or(fallback)
}

/// Resolve host_path through COW (handle_stat), returning the real path.
/// Falls back to host_path if COW is inactive or doesn't match.
async fn cow_resolve(
    state: &Arc<Mutex<SupervisorState>>,
    host_path: &Path,
) -> Result<PathBuf, NotifAction> {
    let st = state.lock().await;
    if let Some(ref cow) = st.cow_branch {
        let host_str = host_path.to_string_lossy();
        if cow.matches(&host_str) {
            return cow
                .handle_stat(&host_str)
                .ok_or(NotifAction::Errno(libc::ENOENT));
        }
    }
    Ok(host_path.to_path_buf())
}

/// Read path arg at `arg_idx`, resolve chroot path using dirfd at `dirfd_idx`.
/// Returns (path_string, host_path) or an appropriate NotifAction.
/// Returns (path_string, host_path, virtual_path).
fn read_and_resolve(
    notif: &SeccompNotif,
    notif_fd: RawFd,
    chroot_root: &Path, // kept as bare Path for internal use
    dirfd_idx: usize,
    path_idx: usize,
) -> Result<(String, PathBuf, PathBuf), NotifAction> {
    let path = read_path(notif, notif.data.args[path_idx], notif_fd)
        .ok_or(NotifAction::Continue)?;
    let dirfd = notif.data.args[dirfd_idx] as i64;
    let (host_path, virtual_path) =
        resolve_chroot_path(notif, dirfd, &path, chroot_root).ok_or(NotifAction::Errno(libc::EACCES))?;
    Ok((path, host_path, virtual_path))
}

/// Perform a libc syscall on a host path; return ReturnValue(0) or Errno.
fn exec_on_host(f: impl FnOnce(*const libc::c_char) -> libc::c_int, host: &Path) -> NotifAction {
    let c = match path_cstr(host, libc::EINVAL) {
        Ok(c) => c,
        Err(a) => return a,
    };
    if f(c.as_ptr()) < 0 {
        NotifAction::Errno(last_errno(libc::EIO))
    } else {
        NotifAction::ReturnValue(0)
    }
}

/// SYS_faccessat2 syscall number (439 on both x86_64 and aarch64).
pub(crate) const SYS_FACCESSAT2: i64 = 439;

// ============================================================
// openat handler
// ============================================================

pub(crate) async fn handle_chroot_open(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let dirfd = notif.data.args[0] as i64;
    let path_ptr = notif.data.args[1];
    let flags = notif.data.args[2];

    let rel_path = match read_path(notif, path_ptr, notif_fd) {
        Some(p) => p,
        None => return NotifAction::Continue,
    };

    // Resolve to get the virtual path for access control.
    let (host_path, virtual_path) = match resolve_chroot_path(notif, dirfd, &rel_path, ctx.root) {
        Some(r) => r,
        None => return NotifAction::Errno(libc::EACCES),
    };

    // Access check: writes need can_write, reads need can_read
    let is_write = (flags as i32 & (libc::O_WRONLY | libc::O_RDWR)) != 0;
    if is_write {
        if !ctx.can_write(&virtual_path) {
            return NotifAction::Errno(libc::EACCES);
        }
    } else if !ctx.can_read(&virtual_path) {
        return NotifAction::Errno(libc::EACCES);
    }

    // COW path — COW operates on host paths, must use libc::open.
    {
        let mut st = state.lock().await;
        if let Some(cow) = st.cow_branch.as_mut() {
            let host_str = host_path.to_string_lossy();
            if cow.matches(&host_str) {
                match cow.handle_open(&host_str, flags) {
                    Ok(Some(real_path)) => {
                        drop(st);
                        let c_path = match path_cstr(&real_path, libc::EINVAL) {
                            Ok(c) => c,
                            Err(a) => return a,
                        };
                        let fd = unsafe { libc::open(c_path.as_ptr(), flags as i32, 0o666) };
                        if fd < 0 {
                            return NotifAction::Errno(last_errno(libc::EIO));
                        }
                        let owned = unsafe { OwnedFd::from_raw_fd(fd) };
                        return NotifAction::InjectFdSend { srcfd: owned };
                    }
                    Ok(None) => {
                        // Fall through to openat2_in_root below. This keeps
                        // directory opens and other non-COW cases confined to
                        // the chroot instead of executing the original host
                        // syscall.
                    }
                    Err(crate::error::BranchError::QuotaExceeded) => {
                        return NotifAction::Errno(libc::ENOSPC);
                    }
                    Err(_) => return NotifAction::Errno(libc::EIO),
                }
            }
        }
    }

    // Open directly via openat2(RESOLVE_IN_ROOT) — single atomic open
    // confined to the chroot root, no resolve-then-reopen TOCTOU gap.
    let vp_str = virtual_path.to_string_lossy();
    let mode = if is_write { 0o666 } else { 0 };
    let fd = match openat2_in_root(ctx.root, &vp_str, flags as i32, mode) {
        Ok(fd) => fd,
        Err(errno) => return NotifAction::Errno(errno),
    };
    let owned = unsafe { OwnedFd::from_raw_fd(fd) };
    NotifAction::InjectFdSend { srcfd: owned }
}

// ============================================================
// execve/execveat handler
// ============================================================

pub(crate) async fn handle_chroot_exec(
    notif: &SeccompNotif,
    _state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let nr = notif.data.nr as i64;
    let (dirfd, path_ptr) = if nr == libc::SYS_execveat {
        (notif.data.args[0] as i64, notif.data.args[1])
    } else {
        (libc::AT_FDCWD as i64, notif.data.args[0])
    };

    let rel_path = match read_path(notif, path_ptr, notif_fd) {
        Some(p) => p,
        None => return NotifAction::Continue,
    };

    // Build the full virtual path from dirfd + relative path.
    let full_path = if Path::new(&rel_path).is_absolute() {
        rel_path
    } else {
        let dirfd32 = dirfd as i32;
        let base_host = if dirfd32 == libc::AT_FDCWD {
            match std::fs::read_link(format!("/proc/{}/cwd", notif.pid)) {
                Ok(p) => p,
                Err(_) => return NotifAction::Errno(libc::EACCES),
            }
        } else {
            match std::fs::read_link(format!("/proc/{}/fd/{}", notif.pid, dirfd)) {
                Ok(p) => p,
                Err(_) => return NotifAction::Errno(libc::EACCES),
            }
        };
        match to_virtual_path(ctx.root, &base_host) {
            Some(base) => base.join(&rel_path).to_string_lossy().to_string(),
            None => return NotifAction::Errno(libc::EACCES),
        }
    };

    let virtual_path = crate::chroot::resolve::confine(&full_path);
    if !ctx.can_read(&virtual_path) {
        return NotifAction::Errno(libc::EACCES);
    }

    // Open the binary directly via openat2(RESOLVE_IN_ROOT). Single atomic
    // open confined to the chroot root — no resolve-then-reopen TOCTOU gap.
    let src_fd = match openat2_in_root(
        ctx.root,
        &virtual_path.to_string_lossy(),
        libc::O_RDONLY | libc::O_CLOEXEC,
        0,
    ) {
        Ok(fd) => fd,
        Err(_) => return NotifAction::Errno(libc::ENOENT),
    };

    // Inject the fd into the child and rewrite the path to /proc/self/fd/N
    // so the kernel loads the ELF from the injected fd.
    let addfd = SeccompNotifAddfd {
        id: notif.id,
        flags: 0,
        srcfd: src_fd as u32,
        newfd: 0,
        newfd_flags: 0, // no O_CLOEXEC — must survive exec
    };
    let child_fd = unsafe {
        libc::ioctl(
            notif_fd,
            SECCOMP_IOCTL_NOTIF_ADDFD as libc::c_ulong,
            &addfd as *const _,
        )
    };
    unsafe { libc::close(src_fd) };

    if child_fd < 0 {
        return NotifAction::Errno(libc::EIO);
    }

    let fd_path = format!("/proc/self/fd/{}\0", child_fd);
    if write_child_mem(notif_fd, notif.id, notif.pid, path_ptr, fd_path.as_bytes()).is_err() {
        return NotifAction::Errno(libc::EFAULT);
    }

    NotifAction::Continue
}

// ============================================================
// Write operation handlers
// ============================================================

pub(crate) async fn handle_chroot_write(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let nr = notif.data.nr as i64;

    if nr == libc::SYS_unlinkat {
        let (_, host_path, vp) = match read_and_resolve(notif, notif_fd, ctx.root, 0, 1) {
            Ok(r) => r,
            Err(a) => return a,
        };
        if !ctx.can_write(&vp) { return NotifAction::Errno(libc::EACCES); }
        let is_dir = (notif.data.args[2] & libc::AT_REMOVEDIR as u64) != 0;

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let s = host_path.to_string_lossy();
                if cow.matches(&s) && cow.handle_unlink(&s, is_dir) {
                    return NotifAction::ReturnValue(0);
                }
            }
        }
        return exec_on_host(
            |p| if is_dir { unsafe { libc::rmdir(p) } } else { unsafe { libc::unlink(p) } },
            &host_path,
        );
    }

    if nr == libc::SYS_mkdirat {
        let (_, host_path, vp) = match read_and_resolve(notif, notif_fd, ctx.root, 0, 1) {
            Ok(r) => r,
            Err(a) => return a,
        };
        if !ctx.can_write(&vp) { return NotifAction::Errno(libc::EACCES); }
        let mode = notif.data.args[2] as u32;

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let s = host_path.to_string_lossy();
                if cow.matches(&s) {
                    match cow.handle_mkdir(&s) {
                        Ok(true) => return NotifAction::ReturnValue(0),
                        Err(crate::error::BranchError::QuotaExceeded) => return NotifAction::Errno(libc::ENOSPC),
                        _ => {}
                    }
                }
            }
        }
        return exec_on_host(|p| unsafe { libc::mkdir(p, mode) }, &host_path);
    }

    if nr == libc::SYS_renameat2 {
        let old_path = match read_path(notif, notif.data.args[1], notif_fd) {
            Some(p) => p,
            None => return NotifAction::Continue,
        };
        let new_path = match read_path(notif, notif.data.args[3], notif_fd) {
            Some(p) => p,
            None => return NotifAction::Continue,
        };
        let (old_host, old_vp) = match resolve_chroot_path(notif, notif.data.args[0] as i64, &old_path, ctx.root) {
            Some(r) => r,
            None => return NotifAction::Errno(libc::EACCES),
        };
        let (new_host, new_vp) = match resolve_chroot_path(notif, notif.data.args[2] as i64, &new_path, ctx.root) {
            Some(r) => r,
            None => return NotifAction::Errno(libc::EACCES),
        };
        if !ctx.can_write(&old_vp) || !ctx.can_write(&new_vp) {
            return NotifAction::Errno(libc::EACCES);
        }

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let old_str = old_host.to_string_lossy();
                if cow.matches(&old_str) {
                    match cow.handle_rename(&old_str, &new_host.to_string_lossy()) {
                        Ok(true) => return NotifAction::ReturnValue(0),
                        Err(crate::error::BranchError::QuotaExceeded) => return NotifAction::Errno(libc::ENOSPC),
                        _ => {}
                    }
                }
            }
        }

        let c_old = match path_cstr(&old_host, libc::EINVAL) { Ok(c) => c, Err(a) => return a };
        let c_new = match path_cstr(&new_host, libc::EINVAL) { Ok(c) => c, Err(a) => return a };
        return if unsafe { libc::rename(c_old.as_ptr(), c_new.as_ptr()) } < 0 {
            NotifAction::Errno(last_errno(libc::EIO))
        } else {
            NotifAction::ReturnValue(0)
        };
    }

    if nr == libc::SYS_symlinkat {
        // symlinkat(target, newdirfd, linkpath)
        let target = match read_path(notif, notif.data.args[0], notif_fd) {
            Some(p) => p,
            None => return NotifAction::Continue,
        };
        let linkpath = match read_path(notif, notif.data.args[2], notif_fd) {
            Some(p) => p,
            None => return NotifAction::Continue,
        };
        let (host_link, link_vp) = match resolve_chroot_path(notif, notif.data.args[1] as i64, &linkpath, ctx.root) {
            Some(r) => r,
            None => return NotifAction::Errno(libc::EACCES),
        };
        if !ctx.can_write(&link_vp) { return NotifAction::Errno(libc::EACCES); }

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let s = host_link.to_string_lossy();
                if cow.matches(&s) {
                    match cow.handle_symlink(&target, &s) {
                        Ok(true) => return NotifAction::ReturnValue(0),
                        Err(crate::error::BranchError::QuotaExceeded) => return NotifAction::Errno(libc::ENOSPC),
                        _ => {}
                    }
                }
            }
        }

        let c_target = match CString::new(target.as_str()) { Ok(c) => c, Err(_) => return NotifAction::Errno(libc::EINVAL) };
        let c_link = match path_cstr(&host_link, libc::EINVAL) { Ok(c) => c, Err(a) => return a };
        return if unsafe { libc::symlink(c_target.as_ptr(), c_link.as_ptr()) } < 0 {
            NotifAction::Errno(last_errno(libc::EIO))
        } else {
            NotifAction::ReturnValue(0)
        };
    }

    if nr == libc::SYS_linkat {
        // linkat(olddirfd, oldpath, newdirfd, newpath, flags)
        let old_path = match read_path(notif, notif.data.args[1], notif_fd) {
            Some(p) => p,
            None => return NotifAction::Continue,
        };
        let new_path = match read_path(notif, notif.data.args[3], notif_fd) {
            Some(p) => p,
            None => return NotifAction::Continue,
        };
        let (old_host, _) = match resolve_chroot_path(notif, notif.data.args[0] as i64, &old_path, ctx.root) {
            Some(r) => r,
            None => return NotifAction::Errno(libc::EACCES),
        };
        let (new_host, new_vp) = match resolve_chroot_path(notif, notif.data.args[2] as i64, &new_path, ctx.root) {
            Some(r) => r,
            None => return NotifAction::Errno(libc::EACCES),
        };
        if !ctx.can_write(&new_vp) { return NotifAction::Errno(libc::EACCES); }

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let s = new_host.to_string_lossy();
                if cow.matches(&s) {
                    match cow.handle_link(&old_host.to_string_lossy(), &s) {
                        Ok(true) => return NotifAction::ReturnValue(0),
                        Err(crate::error::BranchError::QuotaExceeded) => return NotifAction::Errno(libc::ENOSPC),
                        _ => {}
                    }
                }
            }
        }

        let c_old = match path_cstr(&old_host, libc::EINVAL) { Ok(c) => c, Err(a) => return a };
        let c_new = match path_cstr(&new_host, libc::EINVAL) { Ok(c) => c, Err(a) => return a };
        let flags = notif.data.args[4] as i32;
        return if unsafe { libc::linkat(libc::AT_FDCWD, c_old.as_ptr(), libc::AT_FDCWD, c_new.as_ptr(), flags) } < 0 {
            NotifAction::Errno(last_errno(libc::EIO))
        } else {
            NotifAction::ReturnValue(0)
        };
    }

    if nr == libc::SYS_fchmodat {
        let (_, host_path, vp) = match read_and_resolve(notif, notif_fd, ctx.root, 0, 1) {
            Ok(r) => r,
            Err(a) => return a,
        };
        if !ctx.can_write(&vp) { return NotifAction::Errno(libc::EACCES); }
        let mode = (notif.data.args[2] & 0o7777) as u32;

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let s = host_path.to_string_lossy();
                if cow.matches(&s) {
                    match cow.handle_chmod(&s, mode) {
                        Ok(true) => return NotifAction::ReturnValue(0),
                        Err(crate::error::BranchError::QuotaExceeded) => return NotifAction::Errno(libc::ENOSPC),
                        _ => {}
                    }
                }
            }
        }
        return exec_on_host(|p| unsafe { libc::chmod(p, mode) }, &host_path);
    }

    if nr == libc::SYS_fchownat {
        let (_, host_path, vp) = match read_and_resolve(notif, notif_fd, ctx.root, 0, 1) {
            Ok(r) => r,
            Err(a) => return a,
        };
        if !ctx.can_write(&vp) { return NotifAction::Errno(libc::EACCES); }
        let uid = notif.data.args[2] as u32;
        let gid = notif.data.args[3] as u32;

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let s = host_path.to_string_lossy();
                if cow.matches(&s) {
                    match cow.handle_chown(&s, uid, gid) {
                        Ok(true) => return NotifAction::ReturnValue(0),
                        Err(crate::error::BranchError::QuotaExceeded) => return NotifAction::Errno(libc::ENOSPC),
                        _ => {}
                    }
                }
            }
        }
        return exec_on_host(|p| unsafe { libc::chown(p, uid, gid) }, &host_path);
    }

    if nr == libc::SYS_truncate {
        let path = match read_path(notif, notif.data.args[0], notif_fd) {
            Some(p) => p,
            None => return NotifAction::Continue,
        };
        let (host_path, _) = match resolve_chroot_path(notif, libc::AT_FDCWD as i64, &path, ctx.root) {
            Some(r) => r,
            None => return NotifAction::Errno(libc::EACCES),
        };
        let length = notif.data.args[1] as i64;

        {
            let mut st = state.lock().await;
            if let Some(cow) = st.cow_branch.as_mut() {
                let s = host_path.to_string_lossy();
                if cow.matches(&s) {
                    match cow.handle_truncate(&s, length) {
                        Ok(true) => return NotifAction::ReturnValue(0),
                        Err(crate::error::BranchError::QuotaExceeded) => return NotifAction::Errno(libc::ENOSPC),
                        _ => {}
                    }
                }
            }
        }
        return exec_on_host(|p| unsafe { libc::truncate(p, length) }, &host_path);
    }

    NotifAction::Continue
}

// ============================================================
// stat/access handler
// ============================================================

/// Pack struct stat and write to child buffer.
fn stat_and_write(notif: &SeccompNotif, notif_fd: RawFd, path: &Path) -> NotifAction {
    let statbuf_addr = notif.data.args[2];
    let flags = notif.data.args[3];
    let follow = (flags & libc::AT_SYMLINK_NOFOLLOW as u64) == 0;

    let meta = if follow {
        std::fs::metadata(path)
    } else {
        std::fs::symlink_metadata(path)
    };
    let meta = match meta {
        Ok(m) => m,
        Err(_) => return NotifAction::Errno(libc::ENOENT),
    };

    use std::os::unix::fs::MetadataExt;
    let mut buf = vec![0u8; std::mem::size_of::<libc::stat>()];
    let mut off = 0;
    macro_rules! pack_u64 { ($v:expr) => { buf[off..off+8].copy_from_slice(&($v as u64).to_ne_bytes()); off += 8; }; }
    macro_rules! pack_u32 { ($v:expr) => { buf[off..off+4].copy_from_slice(&($v as u32).to_ne_bytes()); off += 4; }; }
    pack_u64!(meta.dev()); pack_u64!(meta.ino()); pack_u64!(meta.nlink());
    pack_u32!(meta.mode()); pack_u32!(meta.uid()); pack_u32!(meta.gid()); pack_u32!(0u32);
    pack_u64!(meta.rdev()); pack_u64!(meta.size() as u64);
    pack_u64!(meta.blksize()); pack_u64!(meta.blocks() as u64);
    pack_u64!(meta.atime() as u64); pack_u64!(meta.atime_nsec() as u64);
    pack_u64!(meta.mtime() as u64); pack_u64!(meta.mtime_nsec() as u64);
    pack_u64!(meta.ctime() as u64); pack_u64!(meta.ctime_nsec() as u64);
    let _ = off;

    if write_child_mem(notif_fd, notif.id, notif.pid, statbuf_addr, &buf).is_err() {
        return NotifAction::Continue;
    }
    NotifAction::ReturnValue(0)
}

pub(crate) async fn handle_chroot_stat(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let nr = notif.data.nr as i64;
    let (_, host_path, vp) = match read_and_resolve(notif, notif_fd, ctx.root, 0, 1) {
        Ok(r) => r,
        Err(a) => return a,
    };
    if !ctx.can_read(&vp) { return NotifAction::Errno(libc::EACCES); }

    let real_path = match cow_resolve(state, &host_path).await {
        Ok(p) => p,
        Err(a) => return a,
    };

    if nr == libc::SYS_faccessat || nr == SYS_FACCESSAT2 {
        return if real_path.exists() || real_path.is_symlink() {
            NotifAction::ReturnValue(0)
        } else {
            NotifAction::Errno(libc::ENOENT)
        };
    }

    stat_and_write(notif, notif_fd, &real_path)
}

// ============================================================
// statx handler
// ============================================================

pub(crate) async fn handle_chroot_statx(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let dirfd = notif.data.args[0] as i64;
    let path_ptr = notif.data.args[1];
    let flags = notif.data.args[2] as i32;
    let mask = notif.data.args[3] as u32;
    let statxbuf_addr = notif.data.args[4];

    let path = match read_path(notif, path_ptr, notif_fd) {
        Some(p) => p,
        None => return NotifAction::Continue,
    };
    if path.is_empty() {
        return NotifAction::Continue;
    }

    let (host_path, vp) = match resolve_chroot_path(notif, dirfd, &path, ctx.root) {
        Some(r) => r,
        None => return NotifAction::Errno(libc::EACCES),
    };
    if !ctx.can_read(&vp) { return NotifAction::Errno(libc::EACCES); }

    let real_path = match cow_resolve(state, &host_path).await {
        Ok(p) => p,
        Err(a) => return a,
    };

    let c_path = match path_cstr(&real_path, libc::ENOENT) {
        Ok(c) => c,
        Err(a) => return a,
    };
    let mut stx_buf = vec![0u8; 256];
    let ret = unsafe {
        libc::syscall(libc::SYS_statx, libc::AT_FDCWD, c_path.as_ptr(), flags, mask, stx_buf.as_mut_ptr())
    };
    if ret < 0 {
        return NotifAction::Errno(last_errno(libc::ENOENT));
    }

    if write_child_mem(notif_fd, notif.id, notif.pid, statxbuf_addr, &stx_buf).is_err() {
        return NotifAction::Continue;
    }
    NotifAction::ReturnValue(0)
}

// ============================================================
// readlink handler
// ============================================================

pub(crate) async fn handle_chroot_readlink(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let dirfd = notif.data.args[0] as i64;
    let path = match read_path(notif, notif.data.args[1], notif_fd) {
        Some(p) => p,
        None => return NotifAction::Continue,
    };
    let buf_addr = notif.data.args[2];
    let bufsiz = (notif.data.args[3] & 0xFFFFFFFF) as usize;

    // Helper: write target bytes to child buffer
    let write_target = |target: &[u8]| -> NotifAction {
        let len = target.len().min(bufsiz);
        if write_child_mem(notif_fd, notif.id, notif.pid, buf_addr, &target[..len]).is_err() {
            return NotifAction::Continue;
        }
        NotifAction::ReturnValue(len as i64)
    };

    // Special case: /proc/self/root -> "/"
    if path == "/proc/self/root" {
        return write_target(b"/");
    }

    // Special case: /proc/self/exe -> strip chroot prefix
    if path == "/proc/self/exe" {
        if let Ok(real_exe) = std::fs::read_link(format!("/proc/{}/exe", notif.pid)) {
            let virtual_exe = to_virtual_path(ctx.root, &real_exe).unwrap_or(real_exe);
            let s = virtual_exe.to_string_lossy();
            return write_target(s.as_bytes());
        }
        return NotifAction::Continue;
    }

    // Resolve the path WITHOUT following the final symlink.  readlink
    // must read the link itself, not its target.  We resolve the parent
    // directory (following intermediate symlinks) and append the filename.
    let full_path = if Path::new(&path).is_absolute() {
        path.clone()
    } else {
        let dirfd32 = dirfd as i32;
        let base_host = if dirfd32 == libc::AT_FDCWD {
            match std::fs::read_link(format!("/proc/{}/cwd", notif.pid)) {
                Ok(p) => p,
                Err(_) => return NotifAction::Errno(libc::EACCES),
            }
        } else {
            match std::fs::read_link(format!("/proc/{}/fd/{}", notif.pid, dirfd)) {
                Ok(p) => p,
                Err(_) => return NotifAction::Errno(libc::EACCES),
            }
        };
        let base_virtual = match to_virtual_path(ctx.root, &base_host) {
            Some(p) => p,
            None => return NotifAction::Errno(libc::EACCES),
        };
        base_virtual.join(&path).to_string_lossy().to_string()
    };
    let confined = crate::chroot::resolve::confine(&full_path);
    let file_name = match confined.file_name() {
        Some(f) => f.to_os_string(),
        None => return NotifAction::Errno(libc::EINVAL),
    };
    let parent = confined.parent().unwrap_or(Path::new("/"));
    let (parent_host, _) = match resolve_in_root(ctx.root, parent.to_str().unwrap_or("/")) {
        Some(r) => r,
        None => return NotifAction::Errno(libc::EACCES),
    };
    let host_path = parent_host.join(&file_name);

    // COW
    {
        let st = state.lock().await;
        if let Some(cow) = st.cow_branch.as_ref() {
            let host_str = host_path.to_string_lossy();
            if cow.matches(&host_str) {
                let target = match cow.handle_readlink(&host_str) {
                    Some(t) => t,
                    None => return NotifAction::Errno(libc::ENOENT),
                };
                drop(st);
                return write_target(target.as_bytes());
            }
        }
    }

    let target = match std::fs::read_link(&host_path) {
        Ok(t) => t,
        Err(_) => return NotifAction::Errno(libc::ENOENT),
    };

    // Strip chroot prefix from absolute targets
    let display = if target.is_absolute() {
        to_virtual_path(ctx.root, &target).unwrap_or(target)
    } else {
        target
    };
    write_target(display.to_string_lossy().as_bytes())
}

// ============================================================
// getdents handler
// ============================================================

pub(crate) async fn handle_chroot_getdents(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let pid = notif.pid;
    let child_fd = (notif.data.args[0] & 0xFFFFFFFF) as u32;
    let buf_addr = notif.data.args[1];
    let buf_size = (notif.data.args[2] & 0xFFFFFFFF) as usize;

    let link_path = format!("/proc/{}/fd/{}", pid, child_fd);
    let target = match std::fs::read_link(&link_path) {
        Ok(t) => t,
        Err(_) => return NotifAction::Continue,
    };

    let host_dir = if to_virtual_path(ctx.root, &target).is_some() {
        target
    } else {
        return NotifAction::Continue;
    };

    // COW delegation
    {
        let st = state.lock().await;
        if let Some(cow) = st.cow_branch.as_ref() {
            if cow.matches(&host_dir.to_string_lossy()) {
                return NotifAction::Continue;
            }
        }
    }

    let cache_key = (pid as i32, child_fd);
    let mut st = state.lock().await;

    if !st.chroot_dir_cache.contains_key(&cache_key) {
        let dir = match std::fs::read_dir(&host_dir) {
            Ok(d) => d,
            Err(_) => return NotifAction::Errno(libc::ENOENT),
        };

        let mut entries = Vec::new();
        let mut d_off: i64 = 0;
        for entry in dir.flatten() {
            let name = entry.file_name();
            d_off += 1;
            let d_type = match entry.file_type() {
                Ok(ft) if ft.is_dir() => DT_DIR,
                Ok(ft) if ft.is_symlink() => DT_LNK,
                _ => DT_REG,
            };
            use std::os::unix::fs::MetadataExt;
            let d_ino = std::fs::symlink_metadata(entry.path())
                .map(|m| m.ino())
                .unwrap_or(0);
            entries.push(build_dirent64(d_ino, d_off, d_type, &name.to_string_lossy()));
        }
        st.chroot_dir_cache.insert(cache_key, entries);
    }

    let entries = match st.chroot_dir_cache.get_mut(&cache_key) {
        Some(e) => e,
        None => return NotifAction::Continue,
    };

    let mut result = Vec::new();
    let mut consumed = 0;
    for entry in entries.iter() {
        if result.len() + entry.len() > buf_size {
            break;
        }
        result.extend_from_slice(entry);
        consumed += 1;
    }
    if consumed > 0 {
        entries.drain(..consumed);
    }
    // Keep empty Vec as EOF sentinel — don't remove.
    drop(st);

    if !result.is_empty() {
        if write_child_mem(notif_fd, notif.id, pid, buf_addr, &result).is_err() {
            return NotifAction::Continue;
        }
    }
    NotifAction::ReturnValue(result.len() as i64)
}

// ============================================================
// chdir handler
// ============================================================

pub(crate) async fn handle_chroot_chdir(
    notif: &SeccompNotif,
    _state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let path_ptr = notif.data.args[0];
    let path = match read_path(notif, path_ptr, notif_fd) {
        Some(p) => p,
        None => return NotifAction::Continue,
    };

    // Build the full virtual path from AT_FDCWD + path.
    let full_path = if Path::new(&path).is_absolute() {
        path
    } else {
        match std::fs::read_link(format!("/proc/{}/cwd", notif.pid)) {
            Ok(cwd) => match to_virtual_path(ctx.root, &cwd) {
                Some(base) => base.join(&path).to_string_lossy().to_string(),
                None => return NotifAction::Errno(libc::EACCES),
            },
            Err(_) => return NotifAction::Errno(libc::EACCES),
        }
    };

    // Open directly via openat2(RESOLVE_IN_ROOT).
    let src_fd = match openat2_in_root(
        ctx.root,
        &full_path,
        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
        0,
    ) {
        Ok(fd) => fd,
        Err(errno) => return NotifAction::Errno(errno),
    };

    // Inject fd into child and rewrite path to /proc/self/fd/N.
    let addfd = SeccompNotifAddfd {
        id: notif.id,
        flags: 0,
        srcfd: src_fd as u32,
        newfd: 0,
        newfd_flags: libc::O_CLOEXEC as u32,
    };
    let child_fd = unsafe {
        libc::ioctl(
            notif_fd,
            SECCOMP_IOCTL_NOTIF_ADDFD as libc::c_ulong,
            &addfd as *const _,
        )
    };
    unsafe { libc::close(src_fd) };

    if child_fd < 0 {
        return NotifAction::Errno(libc::EIO);
    }

    let fd_path = format!("/proc/self/fd/{}\0", child_fd);
    if write_child_mem(notif_fd, notif.id, notif.pid, path_ptr, fd_path.as_bytes()).is_err() {
        return NotifAction::Errno(libc::EFAULT);
    }

    NotifAction::Continue
}

// ============================================================
// getcwd handler
// ============================================================

pub(crate) async fn handle_chroot_getcwd(
    notif: &SeccompNotif,
    _state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let buf_addr = notif.data.args[0];
    let buf_size = (notif.data.args[1] & 0xFFFFFFFF) as usize;

    let cwd = match std::fs::read_link(format!("/proc/{}/cwd", notif.pid)) {
        Ok(c) => c,
        Err(_) => return NotifAction::Continue,
    };

    let virtual_cwd = to_virtual_path(ctx.root, &cwd).unwrap_or_else(|| PathBuf::from("/"));
    let cwd_str = virtual_cwd.to_string_lossy();
    let cwd_bytes = cwd_str.as_bytes();

    if cwd_bytes.len() + 1 > buf_size {
        return NotifAction::Errno(libc::ERANGE);
    }

    let mut write_buf = cwd_bytes.to_vec();
    write_buf.push(0);

    if write_child_mem(notif_fd, notif.id, notif.pid, buf_addr, &write_buf).is_err() {
        return NotifAction::Continue;
    }
    NotifAction::ReturnValue(write_buf.len() as i64)
}

// ============================================================
// statfs handler
// ============================================================

pub(crate) async fn handle_chroot_statfs(
    notif: &SeccompNotif,
    _state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let path_ptr = notif.data.args[0];
    let statfsbuf_addr = notif.data.args[1];
    let path = match read_path(notif, path_ptr, notif_fd) {
        Some(p) => p,
        None => return NotifAction::Continue,
    };

    let (host_path, _) = match resolve_chroot_path(notif, libc::AT_FDCWD as i64, &path, ctx.root) {
        Some(r) => r,
        None => return NotifAction::Errno(libc::EACCES),
    };

    let c_path = match path_cstr(&host_path, libc::ENOENT) {
        Ok(c) => c,
        Err(a) => return a,
    };
    let mut statfs_buf: libc::statfs = unsafe { std::mem::zeroed() };
    if unsafe { libc::statfs(c_path.as_ptr(), &mut statfs_buf) } < 0 {
        return NotifAction::Errno(last_errno(libc::ENOENT));
    }

    let buf_bytes = unsafe {
        std::slice::from_raw_parts(
            &statfs_buf as *const libc::statfs as *const u8,
            std::mem::size_of::<libc::statfs>(),
        )
    };
    if write_child_mem(notif_fd, notif.id, notif.pid, statfsbuf_addr, buf_bytes).is_err() {
        return NotifAction::Continue;
    }
    NotifAction::ReturnValue(0)
}

// ============================================================
// utimensat handler
// ============================================================

pub(crate) async fn handle_chroot_utimensat(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let dirfd = notif.data.args[0] as i64;
    let path_ptr = notif.data.args[1];
    let times_ptr = notif.data.args[2];
    let flags = notif.data.args[3] as i32;

    if path_ptr == 0 {
        return NotifAction::Continue;
    }

    let path = match read_path(notif, path_ptr, notif_fd) {
        Some(p) => p,
        None => return NotifAction::Continue,
    };

    let (host_path, vp) = match resolve_chroot_path(notif, dirfd, &path, ctx.root) {
        Some(r) => r,
        None => return NotifAction::Errno(libc::EACCES),
    };
    if !ctx.can_write(&vp) { return NotifAction::Errno(libc::EACCES); }

    let real_path = match cow_resolve(state, &host_path).await {
        Ok(p) => p,
        Err(a) => return a,
    };

    // Read times from child memory (2 x struct timespec = 32 bytes on x86_64)
    let times = if times_ptr != 0 {
        match read_child_mem(notif_fd, notif.id, notif.pid, times_ptr, 32) {
            Ok(data) => {
                let mut ts: [libc::timespec; 2] = unsafe { std::mem::zeroed() };
                unsafe {
                    std::ptr::copy_nonoverlapping(data.as_ptr(), &mut ts as *mut _ as *mut u8, 32);
                }
                Some(ts)
            }
            Err(_) => return NotifAction::Errno(libc::EFAULT),
        }
    } else {
        None
    };

    let c_path = match path_cstr(&real_path, libc::ENOENT) {
        Ok(c) => c,
        Err(a) => return a,
    };
    let times_raw = times.as_ref().map(|t| t.as_ptr()).unwrap_or(std::ptr::null());
    if unsafe { libc::utimensat(libc::AT_FDCWD, c_path.as_ptr(), times_raw, flags) } < 0 {
        return NotifAction::Errno(last_errno(libc::EIO));
    }
    NotifAction::ReturnValue(0)
}

// ============================================================
// Legacy (non-*at) syscall handlers for musl compatibility
// ============================================================
//
// musl libc uses the older stat/open/access/readlink syscalls instead
// of the *at variants.  These wrappers translate the argument layout
// and delegate to the existing *at handlers.

/// Build a synthetic SeccompNotif with modified args, preserving all other fields.
fn notif_with_args(notif: &SeccompNotif, args: [u64; 6]) -> SeccompNotif {
    let mut copy = *notif;
    copy.data.args = args;
    copy
}

/// SYS_open(path, flags, mode) → handle_chroot_open via openat(AT_FDCWD, path, flags, mode)
pub(crate) async fn handle_chroot_legacy_open(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    // open(path, flags, mode) → openat(AT_FDCWD, path, flags, mode)
    let synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        notif.data.args[1], // flags
        notif.data.args[2], // mode
        0, 0,
    ]);
    handle_chroot_open(&synth, state, notif_fd, ctx).await
}

/// SYS_stat(path, statbuf) → handle_chroot_stat via newfstatat(AT_FDCWD, path, statbuf, 0)
pub(crate) async fn handle_chroot_legacy_stat(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        notif.data.args[1], // statbuf
        0,                  // flags = 0 (follow symlinks)
        0, 0,
    ]);
    handle_chroot_stat(&synth, state, notif_fd, ctx).await
}

/// SYS_lstat(path, statbuf) → handle_chroot_stat via newfstatat(AT_FDCWD, path, statbuf, AT_SYMLINK_NOFOLLOW)
pub(crate) async fn handle_chroot_legacy_lstat(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        notif.data.args[1], // statbuf
        libc::AT_SYMLINK_NOFOLLOW as u64,
        0, 0,
    ]);
    handle_chroot_stat(&synth, state, notif_fd, ctx).await
}

/// SYS_access(path, mode) → handle_chroot_stat via faccessat(AT_FDCWD, path, mode, 0)
pub(crate) async fn handle_chroot_legacy_access(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    // Synthesize as faccessat — reuse SYS_faccessat nr so the handler
    // recognises it as an access check.
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        0,                  // statbuf (unused for faccessat path)
        0,                  // flags
        0, 0,
    ]);
    synth.data.nr = libc::SYS_faccessat as i32;
    handle_chroot_stat(&synth, state, notif_fd, ctx).await
}

/// SYS_readlink(path, buf, bufsiz) → handle_chroot_readlink via readlinkat(AT_FDCWD, path, buf, bufsiz)
pub(crate) async fn handle_chroot_legacy_readlink(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        notif.data.args[1], // buf
        notif.data.args[2], // bufsiz
        0, 0,
    ]);
    handle_chroot_readlink(&synth, state, notif_fd, ctx).await
}

/// SYS_unlink(path) → handle_chroot_write via unlinkat(AT_FDCWD, path, 0)
pub(crate) async fn handle_chroot_legacy_unlink(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        0,                  // flags
        0, 0, 0,
    ]);
    synth.data.nr = libc::SYS_unlinkat as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}

/// SYS_rmdir(path) → handle_chroot_write via unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
pub(crate) async fn handle_chroot_legacy_rmdir(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        libc::AT_REMOVEDIR as u64,
        0, 0, 0,
    ]);
    synth.data.nr = libc::SYS_unlinkat as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}

/// SYS_mkdir(path, mode) → handle_chroot_write via mkdirat(AT_FDCWD, path, mode)
pub(crate) async fn handle_chroot_legacy_mkdir(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        notif.data.args[1], // mode
        0, 0, 0,
    ]);
    synth.data.nr = libc::SYS_mkdirat as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}

/// SYS_rename(oldpath, newpath) → handle_chroot_write via renameat2(AT_FDCWD, old, AT_FDCWD, new, 0)
pub(crate) async fn handle_chroot_legacy_rename(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // oldpath
        libc::AT_FDCWD as u64,
        notif.data.args[1], // newpath
        0, 0,
    ]);
    synth.data.nr = libc::SYS_renameat2 as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}

/// SYS_symlink(target, linkpath) → handle_chroot_write via symlinkat(target, AT_FDCWD, linkpath)
pub(crate) async fn handle_chroot_legacy_symlink(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let mut synth = notif_with_args(notif, [
        notif.data.args[0], // target
        libc::AT_FDCWD as u64,
        notif.data.args[1], // linkpath
        0, 0, 0,
    ]);
    synth.data.nr = libc::SYS_symlinkat as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}

/// SYS_link(oldpath, newpath) → handle_chroot_write via linkat(AT_FDCWD, old, AT_FDCWD, new, 0)
pub(crate) async fn handle_chroot_legacy_link(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // oldpath
        libc::AT_FDCWD as u64,
        notif.data.args[1], // newpath
        0, 0,
    ]);
    synth.data.nr = libc::SYS_linkat as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}

/// SYS_chmod(path, mode) → handle_chroot_write via fchmodat(AT_FDCWD, path, mode)
pub(crate) async fn handle_chroot_legacy_chmod(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
) -> NotifAction {
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        notif.data.args[1], // mode
        0, 0, 0,
    ]);
    synth.data.nr = libc::SYS_fchmodat as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}

/// SYS_chown/lchown(path, uid, gid) → handle_chroot_write via fchownat(AT_FDCWD, path, uid, gid, flags)
pub(crate) async fn handle_chroot_legacy_chown(
    notif: &SeccompNotif,
    state: &Arc<Mutex<SupervisorState>>,
    notif_fd: RawFd,
    ctx: &ChrootCtx<'_>,
    nofollow: bool,
) -> NotifAction {
    let flags = if nofollow { libc::AT_SYMLINK_NOFOLLOW as u64 } else { 0 };
    let mut synth = notif_with_args(notif, [
        libc::AT_FDCWD as u64,
        notif.data.args[0], // path
        notif.data.args[1], // uid
        notif.data.args[2], // gid
        flags,
        0,
    ]);
    synth.data.nr = libc::SYS_fchownat as i32;
    handle_chroot_write(&synth, state, notif_fd, ctx).await
}