starry-kernel 0.5.10

A Linux-compatible OS kernel built on ArceOS unikernel
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
use alloc::{borrow::Cow, sync::Arc, vec, vec::Vec};
use core::{
    ffi::{c_char, c_int},
    task::Context,
};

use ax_errno::{AxError, AxResult, LinuxError};
use ax_fs::{FS_CONTEXT, FileFlags, OpenOptions};
use ax_io::{IoBuf, Read, Seek, SeekFrom};
use ax_task::current;
use axfs_ng_vfs::{NodePermission, NodeType};
use axpoll::{IoEvents, Pollable};
use linux_raw_sys::general::__kernel_off_t;
use starry_vm::{VmMutPtr, VmPtr};
use syscalls::Sysno;

use crate::{
    file::{
        Directory, File, FileLike, Pipe, get_file_like,
        memfd::{F_SEAL_GROW, F_SEAL_WRITE, Memfd},
    },
    mm::{IoVec, IoVectorBuf, UserConstPtr, VmBytesMut},
    task::AsThread,
};

/// Get a [`File`] from fd, converting type-mismatch errors to ESPIPE.
/// Use this for syscalls that require a regular file fd and should return
/// ESPIPE for pipes/sockets (lseek, pread, pwrite, fallocate, etc.).
fn file_or_espipe(fd: c_int) -> AxResult<Arc<File>> {
    File::from_fd(fd).map_err(|e| {
        if e == AxError::IsADirectory || e == AxError::BadFileDescriptor {
            e
        } else {
            AxError::from(LinuxError::ESPIPE)
        }
    })
}

/// Like `file_or_espipe`, but for write operations: converts IsADirectory
/// to BadFileDescriptor because directories cannot be opened for writing.
/// and verifies that the file descriptor is writable.
fn file_or_espipe_write(fd: c_int) -> AxResult<Arc<File>> {
    let f = file_or_espipe(fd).map_err(|e| {
        if e == AxError::IsADirectory {
            AxError::BadFileDescriptor
        } else {
            e
        }
    })?;
    let _ = f.inner().access(FileFlags::WRITE)?;
    Ok(f)
}

fn offset_from_hilo(pos_l: __kernel_off_t, _pos_h: usize) -> __kernel_off_t {
    #[cfg(target_pointer_width = "32")]
    {
        let offset = ((_pos_h as u64) << 32) | (pos_l as u32 as u64);
        offset as i64 as __kernel_off_t
    }

    #[cfg(target_pointer_width = "64")]
    {
        pos_l
    }
}

struct DummyFd;
impl FileLike for DummyFd {
    fn path(&self) -> Cow<'_, str> {
        "anon_inode:[dummy]".into()
    }
}
impl Pollable for DummyFd {
    fn poll(&self) -> IoEvents {
        IoEvents::empty()
    }

    fn register(&self, _context: &mut Context<'_>, _events: IoEvents) {}
}

pub fn sys_dummy_fd(sysno: Sysno) -> AxResult<isize> {
    if current().name().starts_with("qemu-") {
        // We need to be honest to qemu, since it can automatically fallback to
        // other strategies.
        return Err(AxError::Unsupported);
    }
    warn!("Dummy fd created: {sysno}");
    DummyFd.add_to_fd_table(false).map(|fd| fd as isize)
}

/// Read data from the file indicated by `fd`.
///
/// Return the read size if success.
pub fn sys_read(fd: i32, buf: *mut u8, len: usize) -> AxResult<isize> {
    debug!("sys_read <= fd: {fd}, buf: {buf:p}, len: {len}");
    Ok(get_file_like(fd)?.read(&mut VmBytesMut::new(buf, len))? as _)
}

pub fn sys_readv(fd: i32, iov: *const IoVec, iovcnt: usize) -> AxResult<isize> {
    debug!("sys_readv <= fd: {fd}, iovcnt: {iovcnt}");
    let f = get_file_like(fd)?;
    f.read(&mut IoVectorBuf::new(iov, iovcnt)?.into_io())
        .map(|n| n as _)
}

/// Write data to the file indicated by `fd`.
///
/// Return the written size if success.
pub fn sys_write(fd: i32, buf: *mut u8, len: usize) -> AxResult<isize> {
    debug!("sys_write <= fd: {fd}, buf: {buf:p}, len: {len}");
    let data = copy_user_read_buf(buf.cast_const(), len)?;
    Ok(get_file_like(fd)?.write(&mut data.as_slice())? as _)
}

pub fn sys_writev(fd: i32, iov: *const IoVec, iovcnt: usize) -> AxResult<isize> {
    debug!("sys_writev <= fd: {fd}, iovcnt: {iovcnt}");
    let data = copy_user_iov_read_buf(iov, iovcnt)?;
    let f = get_file_like(fd)?;
    f.write(&mut data.as_slice()).map(|n| n as _)
}

pub fn sys_lseek(fd: c_int, offset: __kernel_off_t, whence: c_int) -> AxResult<isize> {
    debug!("sys_lseek <= {fd} {offset} {whence}");
    let pos = match whence {
        0 => {
            if offset < 0 {
                return Err(AxError::InvalidInput);
            }
            SeekFrom::Start(offset as _)
        }
        1 => SeekFrom::Current(offset as _),
        2 => SeekFrom::End(offset as _),
        _ => return Err(AxError::InvalidInput),
    };
    let any_file = get_file_like(fd)?;

    // File::from_fd transparently unwraps Memfd onto its backing File, so
    // memfd fds take this branch and get regular-file seek semantics
    // (lseek, pread/pwrite, fallocate). Without it memfd would fall
    // through to ESPIPE.
    if let Ok(f) = File::from_fd(fd) {
        let off = f.inner().seek(pos)?;
        return Ok(off as _);
    }

    if let Ok(d) = any_file.downcast_arc::<Directory>() {
        let mut off = d.offset.lock();
        let new_pos = match pos {
            SeekFrom::Start(pos) => pos,
            SeekFrom::End(delta) => d
                .inner()
                .len()?
                .checked_add_signed(delta)
                .ok_or(AxError::InvalidInput)?,
            SeekFrom::Current(delta) => {
                off.checked_add_signed(delta).ok_or(AxError::InvalidInput)?
            }
        };
        *off = new_pos;
        return Ok(new_pos as _);
    }

    Err(AxError::from(LinuxError::ESPIPE))
}

pub fn sys_truncate(path: UserConstPtr<c_char>, length: __kernel_off_t) -> AxResult<isize> {
    let path = path.get_as_str()?;
    debug!("sys_truncate <= {path:?} {length}");
    if path.is_empty() {
        return Err(AxError::from(LinuxError::ENOENT));
    }
    if length < 0 {
        return Err(AxError::InvalidInput);
    }
    let file = OpenOptions::new()
        .write(true)
        .open(&FS_CONTEXT.lock(), path)?
        .into_file()?;
    if (length as u64) > u32::MAX as u64 * 4096 {
        return Err(AxError::from(LinuxError::EFBIG));
    }
    // Check write permission against current credentials following the
    // same owner/group/other + root-bypass rules as faccessat2(2).
    let cred = current().as_thread().cred();
    if cred.fsuid != 0 {
        let metadata = file.location().metadata()?;
        let (file_uid, file_gid, file_mode) = (metadata.uid, metadata.gid, metadata.mode);
        let has_write = if cred.fsuid == file_uid {
            file_mode.contains(NodePermission::OWNER_WRITE)
        } else if cred.fsgid == file_gid || cred.groups.contains(&file_gid) {
            file_mode.contains(NodePermission::GROUP_WRITE)
        } else {
            file_mode.contains(NodePermission::OTHER_WRITE)
        };
        if !has_write {
            return Err(AxError::from(LinuxError::EACCES));
        }
    }
    file.access(FileFlags::WRITE)?.set_len(length as _)?;
    Ok(0)
}

pub fn sys_ftruncate(fd: c_int, length: __kernel_off_t) -> AxResult<isize> {
    debug!("sys_ftruncate <= {fd} {length}");
    if length < 0 {
        return Err(AxError::InvalidInput);
    }
    if let Ok(memfd) = Memfd::from_fd(fd) {
        memfd.set_len_sealed(length as u64)?;
        return Ok(0);
    }
    let f = File::from_fd(fd).map_err(|e| {
        if e == AxError::IsADirectory {
            AxError::from(LinuxError::EINVAL)
        } else {
            e
        }
    })?;
    if (length as u64) > u32::MAX as u64 * 4096 {
        return Err(AxError::from(LinuxError::EFBIG));
    }
    f.inner().access(FileFlags::WRITE)?.set_len(length as _)?;
    Ok(0)
}

pub fn sys_fallocate(
    fd: c_int,
    mode: u32,
    offset: __kernel_off_t,
    len: __kernel_off_t,
) -> AxResult<isize> {
    debug!("sys_fallocate <= fd: {fd}, mode: {mode}, offset: {offset}, len: {len}");
    // Validate fd first: invalid/closed/dir/read-only → EBADF, pipe → ESPIPE.
    // Linux errno priority: EBADF/ESPIPE > EOPNOTSUPP > EINVAL.
    let f = file_or_espipe_write(fd)?;
    if mode != 0 {
        return Err(AxError::OperationNotSupported);
    }
    if offset < 0 || len <= 0 {
        return Err(AxError::InvalidInput);
    }
    let end = (offset as u64)
        .checked_add(len as u64)
        .ok_or(AxError::from(LinuxError::EFBIG))?;
    // Reject sizes beyond what ext4 can represent (u32 block numbers × 4 KiB blocks).
    if end > u32::MAX as u64 * 4096 {
        return Err(AxError::from(LinuxError::EFBIG));
    }
    // For memfd fds, enforce the seal mask before changing the size.
    // `F_SEAL_WRITE` already forbids any data-mutating path; `F_SEAL_GROW`
    // additionally forbids a fallocate that would extend EOF. Linux
    // surfaces both as EPERM (memfd_test.c covers this).
    if let Ok(memfd) = Memfd::from_fd(fd) {
        let seals = memfd.get_seals();
        if seals & F_SEAL_WRITE != 0 {
            return Err(AxError::OperationNotPermitted);
        }
        let cur_len = f.inner().backend()?.location().len()?;
        if end > cur_len && seals & F_SEAL_GROW != 0 {
            return Err(AxError::OperationNotPermitted);
        }
    }
    let inner = f.inner();
    let file = inner.access(FileFlags::WRITE)?;
    file.set_len(file.location().len()?.max(end))?;
    Ok(0)
}

pub fn sys_fsync(fd: c_int) -> AxResult<isize> {
    debug!("sys_fsync <= {fd}");
    let any_file = get_file_like(fd)?;
    if let Ok(memfd) = any_file.clone().downcast_arc::<Memfd>() {
        // Linux treats memfd as a regular file for fsync: a successful
        // no-op (the contents are already in memory). Forward to the
        // inner File so any future backing-store changes still hook
        // through one path.
        memfd.inner().inner().sync(false)?;
        return Ok(0);
    }
    if let Ok(f) = any_file.clone().downcast_arc::<File>() {
        f.inner().sync(false)?;
        return Ok(0);
    } else if let Ok(d) = any_file.downcast_arc::<Directory>() {
        d.inner().sync(false)?;
        return Ok(0);
    }
    Err(AxError::from(LinuxError::EINVAL))
}

pub fn sys_fdatasync(fd: c_int) -> AxResult<isize> {
    debug!("sys_fdatasync <= {fd}");
    let any_file = get_file_like(fd)?;
    if let Ok(memfd) = any_file.clone().downcast_arc::<Memfd>() {
        memfd.inner().inner().sync(true)?;
        return Ok(0);
    }
    if let Ok(f) = any_file.clone().downcast_arc::<File>() {
        f.inner().sync(true)?;
        return Ok(0);
    } else if let Ok(d) = any_file.downcast_arc::<Directory>() {
        d.inner().sync(true)?;
        return Ok(0);
    }
    Err(AxError::from(LinuxError::EINVAL))
}

pub fn sys_sync_file_range(fd: c_int, _offset: i64, _nbytes: i64, _flags: u32) -> AxResult<isize> {
    debug!("sys_sync_file_range <= fd: {fd}");
    // sync_file_range(2) is an advisory hint to initiate writeback for a
    // byte range. Until range-based writeback is implemented, keep this as
    // a no-op after basic fd validation rather than turning it into a
    // stronger whole-file fdatasync-style flush (matches the advisory
    // nature documented in the man page). Invalid fds still surface the
    // underlying error (EBADF). Directory fds are accepted to match fsync.
    match File::from_fd(fd) {
        Ok(_) | Err(AxError::IsADirectory) => Ok(0),
        Err(e) => Err(e),
    }
}

pub fn sys_fadvise64(
    fd: c_int,
    offset: __kernel_off_t,
    len: __kernel_off_t,
    advice: u32,
) -> AxResult<isize> {
    debug!("sys_fadvise64 <= fd: {fd}, offset: {offset}, len: {len}, advice: {advice}");
    // Validate fd first: invalid/closed → EBADF, non-file/non-dir → ESPIPE.
    // Linux fadvise64 accepts regular files, directories, and memfd fds
    // (advisory hint).
    let f = get_file_like(fd)?;
    if f.downcast_ref::<File>().is_none()
        && f.downcast_ref::<Directory>().is_none()
        && f.downcast_ref::<Memfd>().is_none()
    {
        return Err(AxError::from(LinuxError::ESPIPE));
    }
    if len < 0 {
        return Err(AxError::InvalidInput);
    }
    if advice > 5 {
        return Err(AxError::InvalidInput);
    }
    Ok(0)
}

pub fn sys_pread64(fd: c_int, buf: *mut u8, len: usize, offset: __kernel_off_t) -> AxResult<isize> {
    let f = file_or_espipe(fd)?;
    if offset < 0 {
        return Err(AxError::InvalidInput);
    }
    let read = f.inner().read_at(VmBytesMut::new(buf, len), offset as _)?;
    Ok(read as _)
}

pub fn sys_pwrite64(
    fd: c_int,
    buf: *const u8,
    len: usize,
    offset: __kernel_off_t,
) -> AxResult<isize> {
    if offset < 0 {
        return Err(AxError::InvalidInput);
    }
    // Route memfd fds through the seal-aware `Memfd::write_at` so
    // `F_SEAL_WRITE`/`F_SEAL_GROW` apply to offset writes the same
    // as they do to seq writes; otherwise `pwrite64` would silently
    // bypass the seal by writing straight to the inner file.
    if let Ok(memfd) = Memfd::from_fd(fd) {
        if len == 0 {
            return Ok(0);
        }
        let data = copy_user_read_buf(buf, len)?;
        let write = memfd.write_at(data.as_slice(), offset as u64)?;
        return Ok(write as _);
    }
    let f = file_or_espipe_write(fd)?;
    if len == 0 {
        return Ok(0);
    }
    let data = copy_user_read_buf(buf, len)?;
    let write = f.inner().write_at(data.as_slice(), offset as _)?;
    Ok(write as _)
}

pub fn sys_preadv(
    fd: c_int,
    iov: *const IoVec,
    iovcnt: usize,
    pos_l: __kernel_off_t,
    pos_h: usize,
) -> AxResult<isize> {
    let offset = offset_from_hilo(pos_l, pos_h);
    // preadv (unlike preadv2) does not accept offset=-1; reject negative offsets.
    if offset < 0 {
        return Err(AxError::InvalidInput);
    }
    sys_preadv2(fd, iov, iovcnt, offset, 0, 0)
}

pub fn sys_pwritev(
    fd: c_int,
    iov: *const IoVec,
    iovcnt: usize,
    pos_l: __kernel_off_t,
    pos_h: usize,
) -> AxResult<isize> {
    let offset = offset_from_hilo(pos_l, pos_h);
    // pwritev (unlike pwritev2) does not accept offset=-1; reject negative offsets.
    if offset < 0 {
        return Err(AxError::InvalidInput);
    }
    sys_pwritev2(fd, iov, iovcnt, offset, 0, 0)
}

/// Validate preadv2/pwritev2 flags.
/// Currently no RWF_* flags are supported; any non-zero value is rejected.
fn validate_rwf_flags(flags: u32) -> AxResult<()> {
    if flags != 0 {
        return Err(AxError::OperationNotSupported);
    }
    Ok(())
}

pub fn sys_preadv2(
    fd: c_int,
    iov: *const IoVec,
    iovcnt: usize,
    pos_l: __kernel_off_t,
    pos_h: usize,
    flags: u32,
) -> AxResult<isize> {
    let offset = offset_from_hilo(pos_l, pos_h);
    debug!("sys_preadv2 <= fd: {fd}, iovcnt: {iovcnt}, offset: {offset}, flags: {flags}");
    validate_rwf_flags(flags)?;
    if offset < -1 {
        return Err(AxError::InvalidInput);
    }
    let mut io_buf = IoVectorBuf::new(iov, iovcnt)?.into_io();
    if offset == -1 {
        // offset == -1: use current file position (like readv)
        let f = get_file_like(fd)?;
        f.read(&mut io_buf).map(|n| n as _)
    } else {
        let f = file_or_espipe(fd)?;
        f.inner().read_at(io_buf, offset as _).map(|n| n as _)
    }
}

pub fn sys_pwritev2(
    fd: c_int,
    iov: *const IoVec,
    iovcnt: usize,
    pos_l: __kernel_off_t,
    pos_h: usize,
    flags: u32,
) -> AxResult<isize> {
    let offset = offset_from_hilo(pos_l, pos_h);
    debug!("sys_pwritev2 <= fd: {fd}, iovcnt: {iovcnt}, offset: {offset}, flags: {flags}");
    validate_rwf_flags(flags)?;
    if offset < -1 {
        return Err(AxError::InvalidInput);
    }
    if offset == -1 {
        // offset == -1: use current file position (like writev)
        let data = copy_user_iov_read_buf(iov, iovcnt)?;
        let f = get_file_like(fd)?;
        f.write(&mut data.as_slice()).map(|n| n as _)
    } else if let Ok(memfd) = Memfd::from_fd(fd) {
        // Route memfd offset writes through the seal-aware path.
        let data = copy_user_iov_read_buf(iov, iovcnt)?;
        memfd
            .write_at(data.as_slice(), offset as u64)
            .map(|n| n as _)
    } else {
        let data = copy_user_iov_read_buf(iov, iovcnt)?;
        let f = file_or_espipe(fd)?;
        f.inner()
            .write_at(data.as_slice(), offset as _)
            .map(|n| n as _)
    }
}

fn copy_user_read_buf(buf: *const u8, len: usize) -> AxResult<Vec<u8>> {
    if len == 0 {
        return Ok(Vec::new());
    }
    Ok(UserConstPtr::<u8>::from(buf).get_as_slice(len)?.to_vec())
}

fn copy_user_iov_read_buf(iov: *const IoVec, iovcnt: usize) -> AxResult<Vec<u8>> {
    let mut src = IoVectorBuf::new(iov, iovcnt)?.into_io();
    let len = src.remaining();
    let mut data = vec![0; len];
    src.read_exact(&mut data)?;
    Ok(data)
}

enum SendFile {
    Direct(Arc<dyn FileLike>),
    Offset(Arc<File>, *mut u64),
    /// Memfd output with an explicit offset. Routed through
    /// `Memfd::write_at` so `F_SEAL_WRITE` / `F_SEAL_GROW` are enforced
    /// the same way as `pwrite`; the plain `Offset` variant unwraps the
    /// memfd to its inner `File` and would silently bypass the seal
    /// check by calling `File::write_at` directly.
    OffsetMemfd(Arc<crate::file::memfd::Memfd>, *mut u64),
}

/// Build the `SendFile` for the *output* end of sendfile / copy_file_range /
/// splice with an explicit offset. When the fd points at a memfd, route
/// writes through the seal-aware [`crate::file::memfd::Memfd`] wrapper
/// instead of unwrapping it to its inner `File` (which would bypass
/// `F_SEAL_WRITE` and `F_SEAL_GROW`).
fn send_offset_out(fd: c_int, offset: *mut u64) -> AxResult<SendFile> {
    let fl = get_file_like(fd)?;
    if let Ok(memfd) = fl.clone().downcast_arc::<crate::file::memfd::Memfd>() {
        return Ok(SendFile::OffsetMemfd(memfd, offset));
    }
    Ok(SendFile::Offset(File::from_fd(fd)?, offset))
}

impl SendFile {
    fn has_data(&self) -> bool {
        match self {
            SendFile::Direct(file) => file.poll(),
            SendFile::Offset(file, ..) => file.poll(),
            SendFile::OffsetMemfd(memfd, ..) => memfd.poll(),
        }
        .contains(IoEvents::IN)
    }

    fn read(&mut self, mut buf: &mut [u8]) -> AxResult<usize> {
        match self {
            SendFile::Direct(file) => file.read(&mut buf),
            SendFile::Offset(file, offset) => {
                let off = offset.vm_read()?;
                let bytes_read = file.inner().read_at(&mut buf, off)?;
                offset.vm_write(off + bytes_read as u64)?;
                Ok(bytes_read)
            }
            SendFile::OffsetMemfd(memfd, offset) => {
                let off = offset.vm_read()?;
                let bytes_read = memfd.inner().inner().read_at(&mut buf, off)?;
                offset.vm_write(off + bytes_read as u64)?;
                Ok(bytes_read)
            }
        }
    }

    fn write(&mut self, mut buf: &[u8]) -> AxResult<usize> {
        match self {
            SendFile::Direct(file) => file.write(&mut buf),
            SendFile::Offset(file, offset) => {
                let off = offset.vm_read()?;
                let bytes_written = file.inner().write_at(buf, off)?;
                offset.vm_write(off + bytes_written as u64)?;
                Ok(bytes_written)
            }
            SendFile::OffsetMemfd(memfd, offset) => {
                let off = offset.vm_read()?;
                let bytes_written = memfd.write_at(buf, off)?;
                offset.vm_write(off + bytes_written as u64)?;
                Ok(bytes_written)
            }
        }
    }
}

fn do_send(mut src: SendFile, mut dst: SendFile, len: usize) -> AxResult<usize> {
    let mut buf = vec![0; 0x1000];
    let mut total_written = 0;
    let mut remaining = len;

    while remaining > 0 {
        if total_written > 0 && !src.has_data() {
            break;
        }
        let to_read = buf.len().min(remaining);
        let bytes_read = match src.read(&mut buf[..to_read]) {
            Ok(n) => n,
            Err(AxError::WouldBlock) if total_written > 0 => break,
            Err(e) => return Err(e),
        };
        if bytes_read == 0 {
            break;
        }

        let bytes_written = dst.write(&buf[..bytes_read])?;
        if bytes_written < bytes_read {
            break;
        }

        total_written += bytes_written;
        remaining -= bytes_written;
    }

    Ok(total_written)
}

pub fn sys_sendfile(out_fd: c_int, in_fd: c_int, offset: *mut u64, len: usize) -> AxResult<isize> {
    debug!(
        "sys_sendfile <= out_fd: {}, in_fd: {}, offset: {}, len: {}",
        out_fd,
        in_fd,
        !offset.is_null(),
        len
    );

    let src = if !offset.is_null() {
        if offset.vm_read()? > u32::MAX as u64 {
            return Err(AxError::InvalidInput);
        }
        SendFile::Offset(File::from_fd(in_fd)?, offset)
    } else {
        SendFile::Direct(get_file_like(in_fd)?)
    };

    let dst = SendFile::Direct(get_file_like(out_fd)?);

    do_send(src, dst, len).map(|n| n as _)
}

pub fn sys_copy_file_range(
    fd_in: c_int,
    off_in: *mut u64,
    fd_out: c_int,
    off_out: *mut u64,
    len: usize,
    flags: u32,
) -> AxResult<isize> {
    debug!(
        "sys_copy_file_range <= fd_in: {}, off_in: {}, fd_out: {}, off_out: {}, len: {}, flags: {}",
        fd_in,
        !off_in.is_null(),
        fd_out,
        !off_out.is_null(),
        len,
        flags
    );

    if flags != 0 {
        return Err(AxError::InvalidInput);
    }

    let remap = |e| match e {
        AxError::BadFileDescriptor | AxError::IsADirectory => e,
        _ => AxError::InvalidInput,
    };
    let file_in = File::from_fd(fd_in).map_err(remap)?;
    let file_out = File::from_fd(fd_out).map_err(remap)?;
    let meta_in = file_in.inner().location().metadata()?;
    let meta_out = file_out.inner().location().metadata()?;

    if meta_in.node_type != NodeType::RegularFile || meta_out.node_type != NodeType::RegularFile {
        return Err(AxError::InvalidInput);
    }
    if file_out.inner().access(FileFlags::APPEND).is_ok() {
        return Err(AxError::BadFileDescriptor);
    }

    if len > 0 && meta_in.device == meta_out.device && meta_in.inode == meta_out.inode {
        let pos_in = if off_in.is_null() {
            file_in.inner().seek(SeekFrom::Current(0))?
        } else {
            off_in.vm_read()?
        };
        let pos_out = if off_out.is_null() {
            file_out.inner().seek(SeekFrom::Current(0))?
        } else {
            off_out.vm_read()?
        };
        if let Some(copy_end) = (len as u64).checked_sub(1) {
            let in_end = pos_in.checked_add(copy_end).ok_or(AxError::InvalidInput)?;
            let out_end = pos_out.checked_add(copy_end).ok_or(AxError::InvalidInput)?;
            if in_end >= pos_out && pos_in <= out_end {
                return Err(AxError::InvalidInput);
            }
        }
    }

    let src = if !off_in.is_null() {
        SendFile::Offset(file_in, off_in)
    } else {
        SendFile::Direct(file_in)
    };

    // Output offset: when fd_out is a memfd, the regular `Offset`
    // variant would unwrap to the inner `File` and bypass seal checks.
    // `send_offset_out` keeps the `Memfd` wrapper so `Memfd::write_at`
    // enforces `F_SEAL_WRITE` / `F_SEAL_GROW`.
    let dst = if !off_out.is_null() {
        send_offset_out(fd_out, off_out)?
    } else {
        SendFile::Direct(get_file_like(fd_out)?)
    };

    do_send(src, dst, len).map(|n| n as _)
}

pub fn sys_splice(
    fd_in: c_int,
    off_in: *mut i64,
    fd_out: c_int,
    off_out: *mut i64,
    len: usize,
    _flags: u32,
) -> AxResult<isize> {
    debug!(
        "sys_splice <= fd_in: {}, off_in: {}, fd_out: {}, off_out: {}, len: {}, flags: {}",
        fd_in,
        !off_in.is_null(),
        fd_out,
        !off_out.is_null(),
        len,
        _flags
    );

    let mut has_pipe = false;

    if DummyFd::from_fd(fd_in).is_ok() || DummyFd::from_fd(fd_out).is_ok() {
        return Err(AxError::BadFileDescriptor);
    }

    let src = if !off_in.is_null() {
        if off_in.vm_read()? < 0 {
            return Err(AxError::InvalidInput);
        }
        SendFile::Offset(File::from_fd(fd_in)?, off_in.cast())
    } else {
        if let Ok(src) = Pipe::from_fd(fd_in) {
            if !src.is_read() {
                return Err(AxError::BadFileDescriptor);
            }
            has_pipe = true;
        }
        if let Ok(file) = File::from_fd(fd_in)
            && file.inner().is_path()
        {
            return Err(AxError::InvalidInput);
        }
        SendFile::Direct(get_file_like(fd_in)?)
    };

    let dst = if !off_out.is_null() {
        if off_out.vm_read()? < 0 {
            return Err(AxError::InvalidInput);
        }
        // Route memfd output through the seal-aware wrapper rather
        // than `File::from_fd`'s auto-unwrap.
        send_offset_out(fd_out, off_out.cast())?
    } else {
        if let Ok(dst) = Pipe::from_fd(fd_out) {
            if !dst.is_write() {
                return Err(AxError::BadFileDescriptor);
            }
            has_pipe = true;
        }
        if let Ok(file) = File::from_fd(fd_out)
            && file.inner().access(FileFlags::APPEND).is_ok()
        {
            return Err(AxError::InvalidInput);
        }
        let f = get_file_like(fd_out)?;
        f.write(&mut b"".as_slice())?;
        SendFile::Direct(f)
    };

    if !has_pipe {
        return Err(AxError::InvalidInput);
    }

    do_send(src, dst, len).map(|n| n as _)
}