syd 3.52.0

rock-solid application kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//
// Syd: rock-solid application kernel
// src/kernel/mod.rs: Secure computing hooks
//
// Copyright (c) 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

macro_rules! syscall_handler {
    ($request:ident, $body:expr) => {{
        let request_id = $request.scmpreq.id;
        let _request_tid = $request.scmpreq.pid();

        #[cfg(feature = "kcov")]
        {
            crate::kcov::abi::kcov_attach(_request_tid);
            crate::kcov::abi::kcov_set_syscall(
                $request.scmpreq.data.syscall.as_raw_syscall().into(),
            );
            let _ = crate::kcov::abi::kcov_enter_for(_request_tid);
            crate::kcov_edge!();
        }

        let result = match $body($request) {
            Ok(result) => result,
            // Harden against UnknownErrno so as not to confuse the
            // Linux API from returning no-op.
            Err(Errno::UnknownErrno) => ScmpNotifResp::new(request_id, 0, -libc::ENOSYS, 0),
            Err(errno) => {
                // `ScmpNotifResp` expects negated errno.
                let errno = (errno as i32).checked_neg().unwrap_or(-libc::ENOSYS);
                ScmpNotifResp::new(request_id, 0, errno, 0)
            }
        };

        #[cfg(feature = "kcov")]
        {
            crate::kcov_edge!();
            let _ = crate::kcov::abi::kcov_exit_for(_request_tid);
        }

        result
    }};
}

/// access(2), faccessat(2) and faccessat2(2) handlers
pub(crate) mod access;

/// chdir(2) and fchdir(2) handlers
pub(crate) mod chdir;

/// chmod(2), fchmod(2), fchmodat(2), and fchmodat2(2) handlers
pub(crate) mod chmod;

/// chown(2), lchown(2), fchown(2), and fchownat(2) handlers
pub(crate) mod chown;

/// chroot(2) handler
pub(crate) mod chroot;

/// exec(3) handlers
pub(crate) mod exec;

/// fanotify_mark(2) handler
pub(crate) mod fanotify;

/// fcntl{,64}(2) handlers
pub(crate) mod fcntl;

/// getdents64(2) handler
pub(crate) mod getdents;

/// inotify_add_watch(2) handler
pub(crate) mod inotify;

/// ioctl(2) handlers
pub(crate) mod ioctl;

/// link(2) and linkat(2) handlers
pub(crate) mod link;

/// Memory syscall handlers
pub(crate) mod mem;

/// memfd_create(2) handler
pub(crate) mod memfd;

/// mkdir(2) and mkdirat(2) handlers
pub(crate) mod mkdir;

/// mknod(2) and mknodat(2) handlers
pub(crate) mod mknod;

/// Network syscall handlers
pub(crate) mod net;

/// creat(2), open(2), openat(2), and openat2(2) handlers
pub(crate) mod open;

/// prctl(2) handler
pub(crate) mod prctl;

/// readlink(2) and readlinkat(2) handlers
pub(crate) mod readlink;

/// rename(2), renameat(2) and renameat2(2) handlers
pub(crate) mod rename;

/// Set UID/GID syscall handlers
pub(crate) mod setid;

/// Shared memory syscall handlers
pub(crate) mod shm;

/// {,rt_}sigaction(2) handler
pub(crate) mod sigaction;

/// Signal syscall handlers
pub(crate) mod signal;

/// stat syscall handlers
pub(crate) mod stat;

/// statfs syscall handlers
pub(crate) mod statfs;

/// symlink(2) and symlinkat(2) handlers
pub(crate) mod symlink;

/// sysinfo(2) handler
pub(crate) mod sysinfo;

/// syslog(2) handler
pub(crate) mod syslog;

/// truncate and allocate handlers
pub(crate) mod truncate;

/// uname(2) handler
pub(crate) mod uname;

/// utime handlers
pub(crate) mod utime;

/// rmdir(2), unlink(2) and unlinkat(2) handlers
pub(crate) mod unlink;

/// xattr handlers
pub(crate) mod xattr;

/// ptrace(2) hooks
pub(crate) mod ptrace;

/// ptrace(2) syscall handler
pub(crate) mod sys_ptrace;

use libseccomp::ScmpNotifResp;
use nix::{
    errno::Errno,
    fcntl::AtFlags,
    sys::{
        signal::{kill, Signal},
        stat::Mode,
    },
    unistd::Pid,
};

use crate::{
    compat::RenameFlags,
    err::cap2no,
    fd::{to_fd, to_valid_fd},
    log::log_is_main,
    log_enabled,
    lookup::{CanonicalPath, FileInfo, FileType},
    notice,
    path::XPath,
    req::{PathArg, PathArgs, SysArg, UNotifyEventRequest},
    sandbox::{Action, Capability, Sandbox, SandboxGuard},
    syslog::LogLevel,
    warn,
};

/// Process the given path argument.
#[expect(clippy::cognitive_complexity)]
pub(crate) fn sandbox_path(
    request: Option<&UNotifyEventRequest>,
    sandbox: &Sandbox,
    pid: Pid,
    path: &XPath,
    caps: Capability,
    syscall_name: &str,
) -> Result<(), Errno> {
    // Validate capabilities.
    let caps_orig = caps & Capability::CAP_GLOB;
    if caps != caps_orig {
        return Err(Errno::EINVAL);
    }

    // Check enabled capabilities.
    let caps = sandbox.getcaps(caps);
    if caps.is_empty() {
        // Protect append-only and masked paths against writes.
        return if caps_orig.can_write() && sandbox.is_write_protected(path) {
            Err(Errno::EPERM)
        } else {
            Ok(())
        };
    }

    // Check for chroot.
    let deny_errno = cap2no(caps);
    if sandbox.is_chroot() {
        return Err(deny_errno);
    }

    // Convert /proc/$pid to /proc/self as necessary.
    let path = path.replace_proc_self(pid);

    // Sandboxing.
    let mut action = Action::Allow;
    for cap in caps {
        let new_action = sandbox.check_path(cap, &path);
        if new_action > action {
            action = new_action;
        }
    }

    if action.is_logging() && log_enabled!(LogLevel::Warn) {
        // Log warn for normal cases.
        // Log info for path hiding/walking unless explicitly specified to warn.
        let is_warn = match caps {
            Capability::CAP_STAT => !matches!(
                sandbox.default_action(Capability::CAP_STAT),
                Action::Filter | Action::Deny
            ),
            Capability::CAP_WALK => !matches!(
                sandbox.default_action(Capability::CAP_WALK),
                Action::Filter | Action::Deny
            ),
            _ => true,
        };

        if let Some(request) = request {
            let args = request.scmpreq.data.args;
            if sandbox.log_scmp() {
                if is_warn {
                    warn!("ctx": "access", "cap": caps, "act": action,
                        "sys": syscall_name,
                        "path": &path, "args": args,
                        "tip": format!("configure `allow/{}+{}'",
                            caps.to_string().to_ascii_lowercase(),
                            path),
                        "req": request);
                } else {
                    notice!("ctx": "access", "cap": caps, "act": action,
                        "sys": syscall_name,
                        "path": &path, "args": args,
                        "tip": format!("configure `allow/{}+{}'",
                            caps.to_string().to_ascii_lowercase(),
                            path),
                        "req": request);
                }
            } else if is_warn {
                warn!("ctx": "access", "cap": caps, "act": action,
                    "sys": syscall_name,
                    "path": &path, "args": args,
                    "tip": format!("configure `allow/{}+{}'",
                        caps.to_string().to_ascii_lowercase(),
                        path),
                    "pid": request.scmpreq.pid);
            } else {
                notice!("ctx": "access", "cap": caps, "act": action,
                    "sys": syscall_name,
                    "path": &path, "args": args,
                    "tip": format!("configure `allow/{}+{}'",
                        caps.to_string().to_ascii_lowercase(),
                        path),
                    "pid": request.scmpreq.pid);
            }
        } else if is_warn {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": syscall_name, "path": &path,
                "tip": format!("configure `allow/{}+{}'",
                    caps.to_string().to_ascii_lowercase(),
                    path),
                "pid": pid.as_raw());
        } else {
            notice!("ctx": "access", "cap": caps, "act": action,
                "sys": syscall_name, "path": &path,
                "tip": format!("configure `allow/{}+{}'",
                    caps.to_string().to_ascii_lowercase(),
                    path),
                "pid": pid.as_raw());
        }
    }

    match action {
        Action::Allow | Action::Warn => {
            // Protect append-only and masked paths against writes.
            if caps_orig.can_write() && sandbox.is_write_protected(&path) {
                return Err(Errno::EPERM);
            }
            Ok(())
        }
        Action::Deny | Action::Filter => Err(deny_errno),
        //Do NOT panic the main thread!
        Action::Panic if log_is_main(std::thread::current().id()) => Err(deny_errno),
        Action::Panic => panic!(),
        Action::Exit => std::process::exit(deny_errno as i32),
        Action::Stop => {
            if let Some(request) = request {
                let _ = request.pidfd_kill(libc::SIGSTOP);
            } else {
                let _ = kill(pid, Some(Signal::SIGSTOP));
            }
            Err(deny_errno)
        }
        Action::Abort => {
            if let Some(request) = request {
                let _ = request.pidfd_kill(libc::SIGABRT);
            } else {
                let _ = kill(pid, Some(Signal::SIGABRT));
            }
            Err(deny_errno)
        }
        Action::Kill => {
            if let Some(request) = request {
                let _ = request.pidfd_kill(libc::SIGKILL);
            } else {
                let _ = kill(pid, Some(Signal::SIGKILL));
            }
            Err(deny_errno)
        }
    }
}

///
/// Handles syscalls related to paths, reducing code redundancy and ensuring a uniform way of dealing with paths.
///
/// # Parameters
///
/// - `request`: User notification request from seccomp.
/// - `syscall_name`: The name of the syscall being handled, used for logging and error reporting.
/// - `arg_mappings`: Non-empty list of argument mappings containing dirfd and path indexes, if applicable.
/// - `handler`: Closure that processes the constructed canonical paths and performs additional syscall-specific operations.
///
/// # Returns
///
/// - `ScmpNotifResp`: Response indicating the result of the syscall handling.
#[expect(clippy::cognitive_complexity)]
pub(crate) fn syscall_path_handler<H>(
    request: UNotifyEventRequest,
    syscall_name: &str,
    path_argv: &[SysArg],
    handler: H,
) -> ScmpNotifResp
where
    H: Fn(PathArgs, &UNotifyEventRequest, SandboxGuard) -> Result<ScmpNotifResp, Errno>,
{
    syscall_handler!(request, |request: UNotifyEventRequest| {
        let req = request.scmpreq;

        // Determine system call capabilities.
        let mut caps = Capability::try_from((req, syscall_name))?;

        // Check if system call is FD-only.
        let is_fd = path_argv.iter().all(|arg| arg.path.is_none());

        // Check for chroot:
        //
        // Delay Chdir to allow the common `cd /` use case right after chroot(2).
        let sandbox = request.get_sandbox();
        if sandbox.is_chroot() && !is_fd && !caps.contains(Capability::CAP_CHDIR) {
            return Err(Errno::ENOENT);
        }

        // If sandboxing for all the selected capabilities is off, return immediately.
        let crypt = sandbox.enabled(Capability::CAP_CRYPT);

        let mut magic = false;
        let mut paths: [Option<PathArg>; 2] = [None, None];
        for (idx, arg) in path_argv.iter().enumerate() {
            // Handle system calls that take a FD only,
            // such as fchmod, fchown, falllocate, ftruncate,
            // fgetxattr, fsetxattr safely and efficiently.
            if arg.path.is_some() {
                let (path, is_magic, is_empty) = request.read_path(&sandbox, *arg)?;
                magic = is_magic;

                if sandbox.is_chroot() {
                    return if caps.contains(Capability::CAP_CHDIR) && path.abs().is_root() {
                        // No-op `cd /` after chroot.
                        Ok(request.return_syscall(0))
                    } else {
                        // arg.path.is_some() -> is_fd = false: Return ENOENT.
                        Err(Errno::ENOENT)
                    };
                }

                let path = PathArg { path, is_empty };
                paths[idx] = Some(path);
            } else if let Some(arg_idx) = arg.dirfd {
                // Validate FD argument.
                let dirfd = if arg.path.is_some() {
                    // AT_FDCWD is OK for *at(2) system calls.
                    to_valid_fd(req.data.args[arg_idx])?
                } else {
                    // AT_FDCWD is NOT OK for fd-only system calls.
                    to_fd(req.data.args[arg_idx])?
                };

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

                    // Handle ftruncate etc. for files with encryption in progress.
                    let crypt_path = if crypt {
                        #[expect(clippy::disallowed_methods)]
                        let files = request.cache.crypt_map.as_ref().unwrap();
                        if let Ok(info) = FileInfo::from_fd(&fd) {
                            let files = files.0.lock().unwrap_or_else(|e| e.into_inner());
                            files
                                .iter()
                                .find_map(|(path, map)| (map.info == info).then(|| path.clone()))
                            // Lock is released here.
                        } else {
                            None
                        }
                    } else {
                        None
                    };

                    let path = if let Some(crypt_path) = crypt_path {
                        CanonicalPath::new_crypt(fd.into(), crypt_path)
                    } else {
                        CanonicalPath::new_fd(fd.into(), req.pid())?
                    };

                    let path = PathArg {
                        path,
                        is_empty: false,
                    };
                    paths[idx] = Some(path);
                } else {
                    let path = CanonicalPath::new_fd(libc::AT_FDCWD.into(), req.pid())?;

                    let path = PathArg {
                        path,
                        is_empty: false,
                    };
                    paths[idx] = Some(path);
                }
            } else {
                unreachable!("BUG: Both dirfd and path are None in SysArg!");
            }
        }

        if magic && sandbox.locked_for(req.pid()) {
            // Sandbox is locked, access denied.
            return Err(Errno::ENOENT);
        }

        if !magic {
            // Call sandbox access checker, skip magic paths.
            match (&paths[0], &paths[1]) {
                (Some(PathArg { path, .. }), None) => {
                    // Adjust capabilities.
                    if caps.contains(Capability::CAP_CREATE) && path.typ.is_some() {
                        caps.remove(Capability::CAP_CREATE);
                    }
                    if caps.contains(Capability::CAP_DELETE) && path.typ.is_none() {
                        caps.remove(Capability::CAP_DELETE);
                    }
                    if caps.contains(Capability::CAP_CHDIR) && path.typ != Some(FileType::Dir) {
                        caps.remove(Capability::CAP_CHDIR);
                    }
                    if caps.contains(Capability::CAP_MKDIR) && path.typ.is_some() {
                        caps.remove(Capability::CAP_MKDIR);
                    }

                    sandbox_path(
                        Some(&request),
                        &sandbox,
                        request.scmpreq.pid(), // Unused when request.is_some()
                        path.abs(),
                        caps,
                        syscall_name,
                    )?
                }
                (Some(PathArg { path: path_0, .. }), Some(PathArg { path: path_1, .. })) => {
                    // link, linkat, rename, renameat, renameat2.
                    //
                    // All of which have RENAME capability.
                    // It's the second argument that is being created/deleted.
                    sandbox_path(
                        Some(&request),
                        &sandbox,
                        request.scmpreq.pid(), // Unused when request.is_some()
                        path_0.abs(),
                        caps,
                        syscall_name,
                    )?;

                    // rename* may overwrite, link* must create.
                    // RENAME_EXCHANGE modifies both paths.
                    if path_1.typ.is_none() || !path_argv[1].fsflags.missing() {
                        let mut caps = Capability::CAP_CREATE;
                        if path_1.typ.is_some() {
                            caps.insert(Capability::CAP_DELETE);
                        }
                        if path_argv[1].fsflags.must_exist() {
                            caps.insert(Capability::CAP_RENAME);
                        }
                        sandbox_path(
                            Some(&request),
                            &sandbox,
                            request.scmpreq.pid(), // Unused when request.is_some()
                            path_1.abs(),
                            caps,
                            syscall_name,
                        )?;
                    }
                }
                _ => unreachable!("BUG: number of path arguments is not 1 or 2!"),
            }
        }

        // Call the system call handler.
        let path_args = PathArgs(paths[0].take(), paths[1].take());
        handler(path_args, &request, sandbox)
    })
}

// Convert system call argument to AtFlags safely.
// Use `valid` to limit set of valid AtFlags.
pub(crate) fn to_atflags(arg: u64, valid: AtFlags) -> Result<AtFlags, Errno> {
    // Linux kernel truncates upper bits.
    #[expect(clippy::cast_possible_truncation)]
    let flags = arg as libc::c_int;

    // Keep invalid flags for future compat!
    let flags = AtFlags::from_bits_retain(flags);

    // Reject unused flags.
    if !flags.difference(valid).is_empty() {
        return Err(Errno::EINVAL);
    }

    Ok(flags)
}

// to_mode that strips unknown bits.
pub(crate) fn to_mode(arg: u64) -> Mode {
    // Linux VFS only honors these chmod bits (07777).
    const S_IALLUGO: libc::mode_t = libc::S_ISUID
        | libc::S_ISGID
        | libc::S_ISVTX
        | libc::S_IRWXU
        | libc::S_IRWXG
        | libc::S_IRWXO;

    #[expect(clippy::cast_possible_truncation)]
    Mode::from_bits_truncate((arg as libc::mode_t) & S_IALLUGO)
}

// to_mode that rejects unknown/invalid bits.
pub(crate) fn to_mode2(arg: u64) -> Result<Mode, Errno> {
    let mode = arg.try_into().or(Err(Errno::EINVAL))?;
    Mode::from_bits(mode).ok_or(Errno::EINVAL)
}

pub(crate) fn to_renameflags(arg: u64) -> Result<RenameFlags, Errno> {
    // Linux kernel truncates upper bits.
    #[expect(clippy::cast_possible_truncation)]
    let flags = RenameFlags::from_bits(arg as u32).ok_or(Errno::EINVAL)?;

    // Fail if (NOREPLACE | WHITEOUT) is combined with EXCHANGE.
    if flags.contains(RenameFlags::RENAME_EXCHANGE)
        && flags.intersects(RenameFlags::RENAME_NOREPLACE | RenameFlags::RENAME_WHITEOUT)
    {
        return Err(Errno::EINVAL);
    }

    Ok(flags)
}

// Convert an 16-bit ID to a regular ID.
//
// u16::MAX maps to u32::MAX (leave unchanged).
pub(crate) fn to_id16(arg: u64) -> u64 {
    to_id16_val(arg).unwrap_or(u64::from(u32::MAX))
}

// Convert an 16-bit ID to a regular ID with validation.
pub(crate) fn to_id16_val(arg: u64) -> Result<u64, Errno> {
    // Linux truncates upper bits.
    // Linux rejects u16::MAX with EINVAL.
    #[expect(clippy::cast_possible_truncation)]
    match arg as u16 {
        u16::MAX => Err(Errno::EINVAL),
        value => Ok(u64::from(value)),
    }
}

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

    #[test]
    fn test_to_atflags() {
        let valid = AtFlags::AT_SYMLINK_NOFOLLOW | AtFlags::AT_EMPTY_PATH | AT_EXECVE_CHECK;
        assert_eq!(to_atflags(valid.bits() as u64, valid), Ok(valid));

        let invalid = AtFlags::AT_REMOVEDIR;
        assert_eq!(to_atflags(invalid.bits() as u64, valid), Err(Errno::EINVAL));
        assert_eq!(
            to_atflags((valid | invalid).bits() as u64, valid),
            Err(Errno::EINVAL)
        );
        assert_eq!(
            to_atflags((valid | invalid).bits() as u64, valid | invalid),
            Ok(valid | invalid)
        );

        assert_eq!(to_atflags(1u64 << 32, valid), Ok(AtFlags::empty()));
        assert_eq!(
            to_atflags(valid.bits() as u64 | (1u64 << 32), valid),
            Ok(valid)
        );
        assert_eq!(to_atflags(1u64 << 33, valid), Ok(AtFlags::empty()));
        assert_eq!(
            to_atflags(
                AtFlags::AT_SYMLINK_NOFOLLOW.bits() as u64 | (0xFFFF_FFFFu64 << 32),
                valid
            ),
            Ok(AtFlags::AT_SYMLINK_NOFOLLOW)
        );
        assert_eq!(to_atflags(u64::MAX, valid), Err(Errno::EINVAL));
    }

    #[test]
    fn test_to_mode_1() {
        assert!(to_mode(0).is_empty());
    }

    #[test]
    fn test_to_mode_2() {
        let mode = to_mode(0o755);
        assert!(mode.contains(Mode::S_IRWXU));
        assert!(mode.contains(Mode::S_IRGRP | Mode::S_IXGRP));
        assert!(mode.contains(Mode::S_IROTH | Mode::S_IXOTH));
    }

    #[test]
    fn test_to_mode_3() {
        let mode = to_mode(0o4755);
        assert!(mode.contains(Mode::S_ISUID));
        assert!(mode.contains(Mode::S_IRWXU));
    }

    #[test]
    fn test_to_mode_4() {
        let mode = to_mode(0o1777);
        assert!(mode.contains(Mode::S_ISVTX));
        assert!(mode.contains(Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO));
    }

    #[test]
    fn test_to_mode_5() {
        // Bits above 07777 must be stripped.
        assert_eq!(to_mode(0o10755), to_mode(0o755));
        assert_eq!(to_mode(0o777 | (1u64 << 32)), to_mode(0o777));
    }

    #[test]
    fn test_to_mode_6() {
        // All valid bits set after truncation.
        let mode = to_mode(u64::MAX);
        assert!(mode.contains(Mode::S_ISUID | Mode::S_ISGID | Mode::S_ISVTX));
        assert!(mode.contains(Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO));
    }

    #[test]
    fn test_to_mode2_1() {
        assert!(to_mode2(0o755).is_ok());
        assert!(to_mode2(0).is_ok());
        assert!(to_mode2(0o7777).is_ok());
    }

    #[test]
    fn test_to_mode2_2() {
        assert_eq!(to_mode2(0o10000), Err(Errno::EINVAL));
    }

    #[test]
    fn test_to_mode2_3() {
        assert_eq!(to_mode2(u64::MAX), Err(Errno::EINVAL));
        assert_eq!(to_mode2(1u64 << 32), Err(Errno::EINVAL));
    }

    #[test]
    fn test_to_renameflags_1() {
        assert_eq!(to_renameflags(0), Ok(RenameFlags::empty()));
    }

    #[test]
    fn test_to_renameflags_2() {
        let result = to_renameflags(RenameFlags::RENAME_NOREPLACE.bits() as u64);
        assert_eq!(result, Ok(RenameFlags::RENAME_NOREPLACE));
    }

    #[test]
    fn test_to_renameflags_3() {
        let result = to_renameflags(RenameFlags::RENAME_EXCHANGE.bits() as u64);
        assert_eq!(result, Ok(RenameFlags::RENAME_EXCHANGE));
    }

    #[test]
    fn test_to_renameflags_4() {
        let result = to_renameflags(RenameFlags::RENAME_WHITEOUT.bits() as u64);
        assert_eq!(result, Ok(RenameFlags::RENAME_WHITEOUT));
    }

    #[test]
    fn test_to_renameflags_5() {
        let arg = (RenameFlags::RENAME_EXCHANGE | RenameFlags::RENAME_NOREPLACE).bits() as u64;
        assert_eq!(to_renameflags(arg), Err(Errno::EINVAL));
    }

    #[test]
    fn test_to_renameflags_6() {
        let arg = (RenameFlags::RENAME_EXCHANGE | RenameFlags::RENAME_WHITEOUT).bits() as u64;
        assert_eq!(to_renameflags(arg), Err(Errno::EINVAL));
    }

    #[test]
    fn test_to_renameflags_7() {
        assert_eq!(to_renameflags(0x08), Err(Errno::EINVAL));
    }

    #[test]
    fn test_to_renameflags_8() {
        let arg = RenameFlags::RENAME_NOREPLACE.bits() as u64 | (1u64 << 32);
        assert_eq!(to_renameflags(arg), Ok(RenameFlags::RENAME_NOREPLACE));
    }
}