starnix_core/task/
syscalls.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::execution::execute_task;
6use crate::mm::{DumpPolicy, MemoryAccessor, MemoryAccessorExt, PAGE_SIZE};
7use crate::ptrace::{
8    PR_SET_PTRACER_ANY, PtraceAllowedPtracers, PtraceAttachType, PtraceOptions, ptrace_attach,
9    ptrace_dispatch, ptrace_traceme,
10};
11use crate::security;
12use crate::signals::syscalls::RUsagePtr;
13use crate::task::{
14    CurrentTask, ExitStatus, NormalPriority, SchedulingPolicy, SeccompAction, SeccompStateValue,
15    SyslogAccess, Task, ThreadGroup, max_priority_for_sched_policy, min_priority_for_sched_policy,
16};
17use crate::vfs::{
18    FdNumber, FileHandle, MountNamespaceFile, PidFdFileObject, UserBuffersOutputBuffer,
19    VecOutputBuffer,
20};
21use starnix_logging::{log_error, log_info, log_trace, track_stub};
22use starnix_sync::{Locked, RwLock, Unlocked};
23use starnix_syscalls::SyscallResult;
24use starnix_task_command::TaskCommand;
25use starnix_types::ownership::WeakRef;
26use starnix_types::time::timeval_from_duration;
27use starnix_uapi::auth::{
28    CAP_SETGID, CAP_SETPCAP, CAP_SETUID, CAP_SYS_ADMIN, CAP_SYS_NICE, CAP_SYS_RESOURCE,
29    CAP_SYS_TTY_CONFIG, Capabilities, Credentials, PTRACE_MODE_READ_REALCREDS, SecureBits,
30};
31use starnix_uapi::errors::{ENAMETOOLONG, Errno};
32use starnix_uapi::file_mode::{Access, AccessCheck, FileMode};
33use starnix_uapi::kcmp::KcmpResource;
34use starnix_uapi::open_flags::OpenFlags;
35use starnix_uapi::resource_limits::Resource;
36use starnix_uapi::signals::{Signal, UncheckedSignal};
37use starnix_uapi::syslog::SyslogAction;
38use starnix_uapi::user_address::{
39    ArchSpecific, MappingMultiArchUserRef, MultiArchUserRef, UserAddress, UserCString,
40    UserCStringPtr, UserRef,
41};
42use starnix_uapi::vfs::ResolveFlags;
43use starnix_uapi::{
44    __user_cap_data_struct, __user_cap_header_struct, _LINUX_CAPABILITY_VERSION_1,
45    _LINUX_CAPABILITY_VERSION_2, _LINUX_CAPABILITY_VERSION_3, AT_EMPTY_PATH, AT_SYMLINK_NOFOLLOW,
46    BPF_MAXINSNS, CLONE_ARGS_SIZE_VER0, CLONE_ARGS_SIZE_VER1, CLONE_ARGS_SIZE_VER2, CLONE_FILES,
47    CLONE_FS, CLONE_NEWNS, CLONE_NEWUTS, CLONE_SETTLS, CLONE_VFORK, NGROUPS_MAX, PR_CAP_AMBIENT,
48    PR_CAP_AMBIENT_CLEAR_ALL, PR_CAP_AMBIENT_IS_SET, PR_CAP_AMBIENT_LOWER, PR_CAP_AMBIENT_RAISE,
49    PR_CAPBSET_DROP, PR_CAPBSET_READ, PR_GET_CHILD_SUBREAPER, PR_GET_DUMPABLE, PR_GET_KEEPCAPS,
50    PR_GET_NAME, PR_GET_NO_NEW_PRIVS, PR_GET_SECCOMP, PR_GET_SECUREBITS, PR_SET_CHILD_SUBREAPER,
51    PR_SET_DUMPABLE, PR_SET_KEEPCAPS, PR_SET_NAME, PR_SET_NO_NEW_PRIVS, PR_SET_PDEATHSIG,
52    PR_SET_PTRACER, PR_SET_SECCOMP, PR_SET_SECUREBITS, PR_SET_TIMERSLACK, PR_SET_VMA,
53    PR_SET_VMA_ANON_NAME, PRIO_PROCESS, PTRACE_ATTACH, PTRACE_SEIZE, PTRACE_TRACEME,
54    RUSAGE_CHILDREN, SCHED_RESET_ON_FORK, SECCOMP_FILTER_FLAG_LOG,
55    SECCOMP_FILTER_FLAG_NEW_LISTENER, SECCOMP_FILTER_FLAG_SPEC_ALLOW, SECCOMP_FILTER_FLAG_TSYNC,
56    SECCOMP_FILTER_FLAG_TSYNC_ESRCH, SECCOMP_GET_ACTION_AVAIL, SECCOMP_GET_NOTIF_SIZES,
57    SECCOMP_MODE_FILTER, SECCOMP_MODE_STRICT, SECCOMP_SET_MODE_FILTER, SECCOMP_SET_MODE_STRICT,
58    c_char, c_int, clone_args, errno, error, gid_t, pid_t, rlimit, rusage, sched_param,
59    sock_filter, uapi, uid_t,
60};
61use static_assertions::const_assert;
62use std::cmp;
63use std::ffi::CString;
64use std::sync::{Arc, LazyLock};
65use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
66
67#[cfg(target_arch = "aarch64")]
68use starnix_uapi::{PR_GET_TAGGED_ADDR_CTRL, PR_SET_TAGGED_ADDR_CTRL, PR_TAGGED_ADDR_ENABLE};
69
70pub type SockFProgPtr =
71    MappingMultiArchUserRef<SockFProg, uapi::sock_fprog, uapi::arch32::sock_fprog>;
72pub type SockFilterPtr = MultiArchUserRef<uapi::sock_filter, uapi::arch32::sock_filter>;
73
74pub struct SockFProg {
75    pub len: u32,
76    pub filter: SockFilterPtr,
77}
78
79uapi::arch_map_data! {
80    BidiTryFrom<SockFProg, sock_fprog> {
81        len = len;
82        filter = filter;
83    }
84}
85
86uapi::check_arch_independent_layout! {
87    sched_param {
88        sched_priority,
89    }
90}
91
92pub fn do_clone(
93    locked: &mut Locked<Unlocked>,
94    current_task: &mut CurrentTask,
95    args: &clone_args,
96) -> Result<pid_t, Errno> {
97    security::check_task_create_access(current_task)?;
98
99    let child_exit_signal = if args.exit_signal == 0 {
100        None
101    } else {
102        Some(Signal::try_from(UncheckedSignal::new(args.exit_signal))?)
103    };
104
105    let mut new_task = current_task.clone_task(
106        locked,
107        args.flags,
108        child_exit_signal,
109        UserRef::<pid_t>::new(UserAddress::from(args.parent_tid)),
110        UserRef::<pid_t>::new(UserAddress::from(args.child_tid)),
111        UserRef::<FdNumber>::new(UserAddress::from(args.pidfd)),
112    )?;
113
114    // Set the result register to 0 for the return value from clone in the
115    // cloned process.
116    new_task.thread_state.registers.set_return_register(0);
117    let (trace_kind, ptrace_state) = current_task.get_ptrace_core_state_for_clone(args);
118
119    if args.stack != 0 {
120        // In clone() the `stack` argument points to the top of the stack, while in clone3()
121        // `stack` points to the bottom of the stack. Therefore, in clone3() we need to add
122        // `stack_size` to calculate the stack pointer. Note that in clone() `stack_size` is 0.
123        new_task
124            .thread_state
125            .registers
126            .set_stack_pointer_register(args.stack.wrapping_add(args.stack_size));
127    }
128
129    if args.flags & (CLONE_SETTLS as u64) != 0 {
130        new_task.thread_state.registers.set_thread_pointer_register(args.tls);
131    }
132
133    let tid = new_task.task.tid;
134    let task_ref = WeakRef::from(&new_task.task);
135    execute_task(locked, new_task, |_, _| Ok(()), |_| {}, ptrace_state)?;
136
137    current_task.ptrace_event(locked, trace_kind, tid as u64);
138
139    if args.flags & (CLONE_VFORK as u64) != 0 {
140        current_task.wait_for_execve(task_ref)?;
141        current_task.ptrace_event(locked, PtraceOptions::TRACEVFORKDONE, tid as u64);
142    }
143
144    Ok(tid)
145}
146
147pub fn sys_clone3(
148    locked: &mut Locked<Unlocked>,
149    current_task: &mut CurrentTask,
150    user_clone_args: UserRef<clone_args>,
151    user_clone_args_size: usize,
152) -> Result<pid_t, Errno> {
153    // Only these specific sized versions are supported.
154    if !(user_clone_args_size == CLONE_ARGS_SIZE_VER0 as usize
155        || user_clone_args_size == CLONE_ARGS_SIZE_VER1 as usize
156        || user_clone_args_size == CLONE_ARGS_SIZE_VER2 as usize)
157    {
158        return error!(EINVAL);
159    }
160
161    // The most recent version of the struct size should match our definition.
162    const_assert!(std::mem::size_of::<clone_args>() == CLONE_ARGS_SIZE_VER2 as usize);
163
164    let clone_args = current_task.read_object_partial(user_clone_args, user_clone_args_size)?;
165    do_clone(locked, current_task, &clone_args)
166}
167
168fn read_c_string_vector(
169    mm: &CurrentTask,
170    user_vector: UserCStringPtr,
171    elem_limit: usize,
172    vec_limit: usize,
173) -> Result<(Vec<CString>, usize), Errno> {
174    let mut user_current = user_vector;
175    let mut vector: Vec<CString> = vec![];
176    let mut vec_size: usize = 0;
177    loop {
178        let user_string = mm.read_multi_arch_ptr(user_current)?;
179        if user_string.is_null() {
180            break;
181        }
182        let string = mm
183            .read_c_string_to_vec(user_string, elem_limit)
184            .map_err(|e| if e.code == ENAMETOOLONG { errno!(E2BIG) } else { e })?;
185        let cstring = CString::new(string).map_err(|_| errno!(EINVAL))?;
186        vec_size =
187            vec_size.checked_add(cstring.as_bytes_with_nul().len()).ok_or_else(|| errno!(E2BIG))?;
188        if vec_size > vec_limit {
189            return error!(E2BIG);
190        }
191        vector.push(cstring);
192        user_current = user_current.next()?;
193    }
194    Ok((vector, vec_size))
195}
196
197pub fn sys_execve(
198    locked: &mut Locked<Unlocked>,
199    current_task: &mut CurrentTask,
200    user_path: UserCString,
201    user_argv: UserCStringPtr,
202    user_environ: UserCStringPtr,
203) -> Result<(), Errno> {
204    sys_execveat(locked, current_task, FdNumber::AT_FDCWD, user_path, user_argv, user_environ, 0)
205}
206
207pub fn sys_execveat(
208    locked: &mut Locked<Unlocked>,
209    current_task: &mut CurrentTask,
210    dir_fd: FdNumber,
211    user_path: UserCString,
212    user_argv: UserCStringPtr,
213    user_environ: UserCStringPtr,
214    flags: u32,
215) -> Result<(), Errno> {
216    if flags & !(AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW) != 0 {
217        return error!(EINVAL);
218    }
219
220    // Calculate the limit for argv and environ size as 1/4 of the stack size, floored at 32 pages.
221    // See the Limits sections in https://man7.org/linux/man-pages/man2/execve.2.html
222    const PAGE_LIMIT: usize = 32;
223    let page_limit_size: usize = PAGE_LIMIT * *PAGE_SIZE as usize;
224    let rlimit = current_task.thread_group().get_rlimit(locked, Resource::STACK);
225    let stack_limit = rlimit / 4;
226    let argv_env_limit = cmp::max(page_limit_size, stack_limit as usize);
227
228    // The limit per argument or environment variable is 32 pages.
229    // See the Limits sections in https://man7.org/linux/man-pages/man2/execve.2.html
230    let (argv, argv_size) = if user_argv.is_null() {
231        (Vec::new(), 0)
232    } else {
233        read_c_string_vector(current_task, user_argv, page_limit_size, argv_env_limit)?
234    };
235
236    let (environ, _) = if user_environ.is_null() {
237        (Vec::new(), 0)
238    } else {
239        read_c_string_vector(
240            current_task,
241            user_environ,
242            page_limit_size,
243            argv_env_limit - argv_size,
244        )?
245    };
246
247    let path = &current_task.read_path(user_path)?;
248
249    log_trace!(argv:?, environ:?, flags:?; "execveat({dir_fd}, {path})");
250
251    let mut open_flags = OpenFlags::RDONLY;
252
253    if flags & AT_SYMLINK_NOFOLLOW != 0 {
254        open_flags |= OpenFlags::NOFOLLOW;
255    }
256
257    let executable = if path.is_empty() {
258        if flags & AT_EMPTY_PATH == 0 {
259            // If AT_EMPTY_PATH is not set, this is an error.
260            return error!(ENOENT);
261        }
262
263        // O_PATH allowed for:
264        //
265        //   Passing the file descriptor as the dirfd argument of
266        //   openat() and the other "*at()" system calls.  This
267        //   includes linkat(2) with AT_EMPTY_PATH (or via procfs
268        //   using AT_SYMLINK_FOLLOW) even if the file is not a
269        //   directory.
270        //
271        // See https://man7.org/linux/man-pages/man2/open.2.html
272        let file = current_task.files.get_allowing_opath(dir_fd)?;
273
274        // We are forced to reopen the file with O_RDONLY to get access to the underlying VMO.
275        // Note that skip the access check in the arguments in case the file mode does
276        // not actually have the read permission bit.
277        //
278        // This can happen because a file could have --x--x--x mode permissions and then
279        // be opened with O_PATH. Internally, the file operations would all be stubbed out
280        // for that file, which is undesirable here.
281        //
282        // See https://man7.org/linux/man-pages/man3/fexecve.3.html#DESCRIPTION
283        file.name.open(
284            locked,
285            current_task,
286            OpenFlags::RDONLY,
287            AccessCheck::check_for(Access::EXEC),
288        )?
289    } else {
290        current_task.open_file_at(
291            locked,
292            dir_fd,
293            path.as_ref(),
294            open_flags,
295            FileMode::default(),
296            ResolveFlags::empty(),
297            AccessCheck::check_for(Access::EXEC),
298        )?
299    };
300
301    // This path can affect script resolution (the path is appended to the script args)
302    // and the auxiliary value `AT_EXECFN` from the syscall `getauxval()`
303    let path = if dir_fd == FdNumber::AT_FDCWD {
304        // The file descriptor is CWD, so the path is exactly
305        // what the user specified.
306        path.to_vec()
307    } else {
308        // The path is `/dev/fd/N/P` where N is the file descriptor
309        // number and P is the user-provided path (if relative and non-empty).
310        //
311        // See https://man7.org/linux/man-pages/man2/execveat.2.html#NOTES
312        match path.first() {
313            Some(b'/') => {
314                // The user-provided path is absolute, so dir_fd is ignored.
315                path.to_vec()
316            }
317            Some(_) => {
318                // User-provided path is relative, append it.
319                let mut new_path = format!("/dev/fd/{}/", dir_fd.raw()).into_bytes();
320                new_path.append(&mut path.to_vec());
321                new_path
322            }
323            // User-provided path is empty
324            None => format!("/dev/fd/{}", dir_fd.raw()).into_bytes(),
325        }
326    };
327
328    let path = CString::new(path).map_err(|_| errno!(EINVAL))?;
329
330    current_task.exec(locked, executable, path, argv, environ)?;
331    Ok(())
332}
333
334pub fn sys_getcpu(
335    _locked: &mut Locked<Unlocked>,
336    current_task: &CurrentTask,
337    cpu_out: UserRef<u32>,
338    node_out: UserRef<u32>,
339) -> Result<(), Errno> {
340    // "When either cpu or node is NULL nothing is written to the respective pointer."
341    // from https://man7.org/linux/man-pages/man2/getcpu.2.html
342    if !cpu_out.is_null() {
343        let thread_stats = current_task
344            .thread
345            .read()
346            .as_ref()
347            .expect("current thread is never None when executing")
348            .stats()
349            .map_err(|e| errno!(EINVAL, format!("getting thread stats failed {e:?}")))?;
350        current_task.write_object(cpu_out, &thread_stats.last_scheduled_cpu)?;
351    }
352    if !node_out.is_null() {
353        // Zircon does not yet have a concept of NUMA task scheduling, always tell userspace that
354        // it's on the "first" node which should be true for non-NUMA systems.
355        track_stub!(TODO("https://fxbug.dev/325643815"), "getcpu() numa node");
356        current_task.write_object(node_out, &0)?;
357    }
358    Ok(())
359}
360
361pub fn sys_getpid(
362    _locked: &mut Locked<Unlocked>,
363    current_task: &CurrentTask,
364) -> Result<pid_t, Errno> {
365    Ok(current_task.get_pid())
366}
367
368pub fn sys_gettid(
369    _locked: &mut Locked<Unlocked>,
370    current_task: &CurrentTask,
371) -> Result<pid_t, Errno> {
372    Ok(current_task.get_tid())
373}
374
375pub fn sys_getppid(
376    _locked: &mut Locked<Unlocked>,
377    current_task: &CurrentTask,
378) -> Result<pid_t, Errno> {
379    Ok(current_task.thread_group().read().get_ppid())
380}
381
382fn get_task_or_current(current_task: &CurrentTask, pid: pid_t) -> WeakRef<Task> {
383    if pid == 0 { current_task.weak_task() } else { current_task.get_task(pid) }
384}
385
386pub fn sys_getsid(
387    _locked: &mut Locked<Unlocked>,
388    current_task: &CurrentTask,
389    pid: pid_t,
390) -> Result<pid_t, Errno> {
391    let weak = get_task_or_current(current_task, pid);
392    let target_task = Task::from_weak(&weak)?;
393    security::check_task_getsid(current_task, &target_task)?;
394    let sid = target_task.thread_group().read().process_group.session.leader;
395    Ok(sid)
396}
397
398pub fn sys_getpgid(
399    _locked: &mut Locked<Unlocked>,
400    current_task: &CurrentTask,
401    pid: pid_t,
402) -> Result<pid_t, Errno> {
403    let weak = get_task_or_current(current_task, pid);
404    let task = Task::from_weak(&weak)?;
405
406    security::check_getpgid_access(current_task, &task)?;
407    let pgid = task.thread_group().read().process_group.leader;
408    Ok(pgid)
409}
410
411pub fn sys_setpgid(
412    locked: &mut Locked<Unlocked>,
413    current_task: &CurrentTask,
414    pid: pid_t,
415    pgid: pid_t,
416) -> Result<(), Errno> {
417    let weak = get_task_or_current(current_task, pid);
418    let task = Task::from_weak(&weak)?;
419
420    current_task.thread_group().setpgid(locked, current_task, &task, pgid)?;
421    Ok(())
422}
423
424impl CurrentTask {
425    /// Returns true if the `current_task`'s effective user ID (EUID) is the same as the
426    /// EUID or UID of the `target_task`. We describe this as the current task being
427    /// "EUID-friendly" to the target and it enables actions to be performed that would
428    /// otherwise require additional privileges.
429    ///
430    /// See "The caller needs an effective user ID equal to the real user ID or effective
431    /// user ID of the [target]" at sched_setaffinity(2), comparable language at
432    /// setpriority(2), more ambiguous language at sched_setscheduler(2), and no
433    /// particular specification at sched_setparam(2).
434    fn is_euid_friendly_with(&self, target_task: &Task) -> bool {
435        let self_creds = self.current_creds();
436        let target_creds = target_task.real_creds();
437        self_creds.euid == target_creds.uid || self_creds.euid == target_creds.euid
438    }
439}
440
441// A non-root process is allowed to set any of its three uids to the value of any other. The
442// CAP_SETUID capability bypasses these checks and allows setting any uid to any integer. Likewise
443// for gids.
444fn new_uid_allowed(current_task: &CurrentTask, uid: uid_t) -> bool {
445    let current_creds = current_task.current_creds();
446    uid == current_creds.uid
447        || uid == current_creds.euid
448        || uid == current_creds.saved_uid
449        || security::is_task_capable_noaudit(current_task, CAP_SETUID)
450}
451
452fn new_gid_allowed(current_task: &CurrentTask, gid: gid_t) -> bool {
453    let current_creds = current_task.current_creds();
454    gid == current_creds.gid
455        || gid == current_creds.egid
456        || gid == current_creds.saved_gid
457        || security::is_task_capable_noaudit(current_task, CAP_SETGID)
458}
459
460pub fn sys_getuid(
461    _locked: &mut Locked<Unlocked>,
462    current_task: &CurrentTask,
463) -> Result<uid_t, Errno> {
464    Ok(current_task.current_creds().uid)
465}
466
467pub fn sys_getgid(
468    _locked: &mut Locked<Unlocked>,
469    current_task: &CurrentTask,
470) -> Result<gid_t, Errno> {
471    Ok(current_task.current_creds().gid)
472}
473
474pub fn sys_setuid(
475    _locked: &mut Locked<Unlocked>,
476    current_task: &CurrentTask,
477    uid: uid_t,
478) -> Result<(), Errno> {
479    if uid == gid_t::MAX {
480        return error!(EINVAL);
481    }
482    if !new_uid_allowed(&current_task, uid) {
483        return error!(EPERM);
484    }
485
486    let mut creds = Credentials::clone(&current_task.current_creds());
487    let prev = creds.copy_user_credentials();
488    creds.euid = uid;
489    creds.fsuid = uid;
490    if security::is_task_capable_noaudit(current_task, CAP_SETUID) {
491        creds.uid = uid;
492        creds.saved_uid = uid;
493    }
494
495    creds.update_capabilities(prev);
496    current_task.set_creds(creds);
497    Ok(())
498}
499
500pub fn sys_setgid(
501    _locked: &mut Locked<Unlocked>,
502    current_task: &CurrentTask,
503    gid: gid_t,
504) -> Result<(), Errno> {
505    if gid == gid_t::MAX {
506        return error!(EINVAL);
507    }
508    if !new_gid_allowed(&current_task, gid) {
509        return error!(EPERM);
510    }
511
512    let mut creds = Credentials::clone(&current_task.current_creds());
513    creds.egid = gid;
514    creds.fsgid = gid;
515    if security::is_task_capable_noaudit(current_task, CAP_SETGID) {
516        creds.gid = gid;
517        creds.saved_gid = gid;
518    }
519    current_task.set_creds(creds);
520    Ok(())
521}
522
523pub fn sys_geteuid(
524    _locked: &mut Locked<Unlocked>,
525    current_task: &CurrentTask,
526) -> Result<uid_t, Errno> {
527    Ok(current_task.current_creds().euid)
528}
529
530pub fn sys_getegid(
531    _locked: &mut Locked<Unlocked>,
532    current_task: &CurrentTask,
533) -> Result<gid_t, Errno> {
534    Ok(current_task.current_creds().egid)
535}
536
537pub fn sys_setfsuid(
538    _locked: &mut Locked<Unlocked>,
539    current_task: &CurrentTask,
540    fsuid: uid_t,
541) -> Result<uid_t, Errno> {
542    let mut creds = Credentials::clone(&current_task.current_creds());
543    let prev = creds.copy_user_credentials();
544    if fsuid != u32::MAX && new_uid_allowed(&current_task, fsuid) {
545        creds.fsuid = fsuid;
546        creds.update_capabilities(prev);
547        current_task.set_creds(creds);
548    }
549
550    Ok(prev.fsuid)
551}
552
553pub fn sys_setfsgid(
554    _locked: &mut Locked<Unlocked>,
555    current_task: &CurrentTask,
556    fsgid: gid_t,
557) -> Result<gid_t, Errno> {
558    let mut creds = Credentials::clone(&current_task.current_creds());
559    let prev = creds.copy_user_credentials();
560    let prev_fsgid = creds.fsgid;
561
562    if fsgid != u32::MAX && new_gid_allowed(&current_task, fsgid) {
563        creds.fsgid = fsgid;
564        creds.update_capabilities(prev);
565        current_task.set_creds(creds);
566    }
567
568    Ok(prev_fsgid)
569}
570
571pub fn sys_getresuid(
572    _locked: &mut Locked<Unlocked>,
573    current_task: &CurrentTask,
574    ruid_addr: UserRef<uid_t>,
575    euid_addr: UserRef<uid_t>,
576    suid_addr: UserRef<uid_t>,
577) -> Result<(), Errno> {
578    let creds = current_task.current_creds();
579    current_task.write_object(ruid_addr, &creds.uid)?;
580    current_task.write_object(euid_addr, &creds.euid)?;
581    current_task.write_object(suid_addr, &creds.saved_uid)?;
582    Ok(())
583}
584
585pub fn sys_getresgid(
586    _locked: &mut Locked<Unlocked>,
587    current_task: &CurrentTask,
588    rgid_addr: UserRef<gid_t>,
589    egid_addr: UserRef<gid_t>,
590    sgid_addr: UserRef<gid_t>,
591) -> Result<(), Errno> {
592    let creds = current_task.current_creds();
593    current_task.write_object(rgid_addr, &creds.gid)?;
594    current_task.write_object(egid_addr, &creds.egid)?;
595    current_task.write_object(sgid_addr, &creds.saved_gid)?;
596    Ok(())
597}
598
599pub fn sys_setreuid(
600    _locked: &mut Locked<Unlocked>,
601    current_task: &CurrentTask,
602    ruid: uid_t,
603    euid: uid_t,
604) -> Result<(), Errno> {
605    let allowed = |uid| uid == u32::MAX || new_uid_allowed(&current_task, uid);
606    if !allowed(ruid) || !allowed(euid) {
607        return error!(EPERM);
608    }
609
610    let mut creds = Credentials::clone(&current_task.current_creds());
611    let prev = creds.copy_user_credentials();
612    let mut is_ruid_set = false;
613    if ruid != u32::MAX {
614        creds.uid = ruid;
615        is_ruid_set = true;
616    }
617    if euid != u32::MAX {
618        creds.euid = euid;
619        creds.fsuid = euid;
620    }
621
622    if is_ruid_set || prev.uid != euid {
623        creds.saved_uid = creds.euid;
624    }
625
626    creds.update_capabilities(prev);
627    current_task.set_creds(creds);
628    Ok(())
629}
630
631pub fn sys_setregid(
632    _locked: &mut Locked<Unlocked>,
633    current_task: &CurrentTask,
634    rgid: gid_t,
635    egid: gid_t,
636) -> Result<(), Errno> {
637    let allowed = |gid| gid == u32::MAX || new_gid_allowed(&current_task, gid);
638    if !allowed(rgid) || !allowed(egid) {
639        return error!(EPERM);
640    }
641
642    let mut creds = Credentials::clone(&current_task.current_creds());
643    let previous_rgid = creds.gid;
644    let mut is_rgid_set = false;
645    if rgid != u32::MAX {
646        creds.gid = rgid;
647        is_rgid_set = true;
648    }
649    if egid != u32::MAX {
650        creds.egid = egid;
651        creds.fsgid = egid;
652    }
653
654    if is_rgid_set || previous_rgid != egid {
655        creds.saved_gid = creds.egid;
656    }
657
658    current_task.set_creds(creds);
659    Ok(())
660}
661
662pub fn sys_setresuid(
663    _locked: &mut Locked<Unlocked>,
664    current_task: &CurrentTask,
665    ruid: uid_t,
666    euid: uid_t,
667    suid: uid_t,
668) -> Result<(), Errno> {
669    let allowed = |uid| uid == u32::MAX || new_uid_allowed(&current_task, uid);
670    if !allowed(ruid) || !allowed(euid) || !allowed(suid) {
671        return error!(EPERM);
672    }
673
674    let mut creds = Credentials::clone(&current_task.current_creds());
675    let prev = creds.copy_user_credentials();
676    if ruid != u32::MAX {
677        creds.uid = ruid;
678    }
679    if euid != u32::MAX {
680        creds.euid = euid;
681        creds.fsuid = euid;
682    }
683    if suid != u32::MAX {
684        creds.saved_uid = suid;
685    }
686    creds.update_capabilities(prev);
687    current_task.set_creds(creds);
688    Ok(())
689}
690
691pub fn sys_setresgid(
692    _locked: &mut Locked<Unlocked>,
693    current_task: &CurrentTask,
694    rgid: gid_t,
695    egid: gid_t,
696    sgid: gid_t,
697) -> Result<(), Errno> {
698    let allowed = |gid| gid == u32::MAX || new_gid_allowed(&current_task, gid);
699    if !allowed(rgid) || !allowed(egid) || !allowed(sgid) {
700        return error!(EPERM);
701    }
702
703    let mut creds = Credentials::clone(&current_task.current_creds());
704    if rgid != u32::MAX {
705        creds.gid = rgid;
706    }
707    if egid != u32::MAX {
708        creds.egid = egid;
709        creds.fsgid = egid;
710    }
711    if sgid != u32::MAX {
712        creds.saved_gid = sgid;
713    }
714    current_task.set_creds(creds);
715    Ok(())
716}
717
718pub fn sys_exit(
719    _locked: &mut Locked<Unlocked>,
720    current_task: &CurrentTask,
721    code: i32,
722) -> Result<(), Errno> {
723    // Only change the current exit status if this has not been already set by exit_group, as
724    // otherwise it has priority.
725    current_task.write().set_exit_status_if_not_already(ExitStatus::Exit(code as u8));
726    Ok(())
727}
728
729pub fn sys_exit_group(
730    locked: &mut Locked<Unlocked>,
731    current_task: &mut CurrentTask,
732    code: i32,
733) -> Result<(), Errno> {
734    current_task.thread_group_exit(locked, ExitStatus::Exit(code as u8));
735    Ok(())
736}
737
738pub fn sys_sched_getscheduler(
739    _locked: &mut Locked<Unlocked>,
740    current_task: &CurrentTask,
741    pid: pid_t,
742) -> Result<u32, Errno> {
743    if pid < 0 {
744        return error!(EINVAL);
745    }
746
747    let weak = get_task_or_current(current_task, pid);
748    let target_task = Task::from_weak(&weak)?;
749    security::check_getsched_access(current_task, target_task.as_ref())?;
750    let current_scheduler_state = target_task.read().scheduler_state;
751    Ok(current_scheduler_state.policy_for_sched_getscheduler())
752}
753
754pub fn sys_sched_setscheduler(
755    locked: &mut Locked<Unlocked>,
756    current_task: &CurrentTask,
757    pid: pid_t,
758    policy: u32,
759    param: UserRef<sched_param>,
760) -> Result<(), Errno> {
761    // Parse & validate the arguments.
762    if pid < 0 || param.is_null() {
763        return error!(EINVAL);
764    }
765
766    let weak = get_task_or_current(current_task, pid);
767    let target_task = Task::from_weak(&weak)?;
768
769    let reset_on_fork = policy & SCHED_RESET_ON_FORK != 0;
770
771    let policy = SchedulingPolicy::try_from(policy & !SCHED_RESET_ON_FORK)?;
772    let realtime_priority =
773        policy.realtime_priority_from(current_task.read_object(param)?.sched_priority)?;
774
775    // TODO: https://fxbug.dev/425143440 - we probably want to improve the locking here.
776    let current_state = target_task.read().scheduler_state;
777
778    // Check capabilities and permissions, if required, for the operation.
779    let euid_friendly = current_task.is_euid_friendly_with(&target_task);
780    let strengthening = current_state.realtime_priority < realtime_priority;
781    let rlimited = strengthening
782        && realtime_priority
783            .exceeds(target_task.thread_group().get_rlimit(locked, Resource::RTPRIO));
784    let clearing_reset_on_fork = current_state.reset_on_fork && !reset_on_fork;
785    let caught_in_idle_trap = current_state.policy == SchedulingPolicy::Idle
786        && policy != SchedulingPolicy::Idle
787        && current_state
788            .normal_priority
789            .exceeds(target_task.thread_group().get_rlimit(locked, Resource::NICE));
790    if !euid_friendly || rlimited || clearing_reset_on_fork || caught_in_idle_trap {
791        security::check_task_capable(current_task, CAP_SYS_NICE)?;
792    }
793
794    security::check_setsched_access(current_task, &target_task)?;
795
796    // Apply the new scheduler configuration to the task.
797    target_task.set_scheduler_policy_priority_and_reset_on_fork(
798        policy,
799        realtime_priority,
800        reset_on_fork,
801    )?;
802
803    Ok(())
804}
805
806const CPU_SET_SIZE: usize = 128;
807
808#[repr(C)]
809#[derive(Debug, Copy, Clone, IntoBytes, FromBytes, KnownLayout, Immutable)]
810pub struct CpuSet {
811    bits: [u8; CPU_SET_SIZE],
812}
813
814impl Default for CpuSet {
815    fn default() -> Self {
816        Self { bits: [0; CPU_SET_SIZE] }
817    }
818}
819
820fn check_cpu_set_alignment(current_task: &CurrentTask, cpusetsize: u32) -> Result<(), Errno> {
821    let alignment = if current_task.is_arch32() { 4 } else { 8 };
822    if cpusetsize < alignment || cpusetsize % alignment != 0 {
823        return error!(EINVAL);
824    }
825    Ok(())
826}
827
828fn get_default_cpu_set() -> CpuSet {
829    let mut result = CpuSet::default();
830    let mut cpus_count = zx::system_get_num_cpus();
831    let cpus_count_max = (CPU_SET_SIZE * 8) as u32;
832    if cpus_count > cpus_count_max {
833        log_error!("cpus_count={cpus_count}, greater than the {cpus_count_max} max supported.");
834        cpus_count = cpus_count_max;
835    }
836    let mut index = 0;
837    while cpus_count > 0 {
838        let count = std::cmp::min(cpus_count, 8);
839        let (shl, overflow) = 1_u8.overflowing_shl(count);
840        let mask = if overflow { u8::max_value() } else { shl - 1 };
841        result.bits[index] = mask;
842        index += 1;
843        cpus_count -= count;
844    }
845    result
846}
847
848pub fn sys_sched_getaffinity(
849    _locked: &mut Locked<Unlocked>,
850    current_task: &CurrentTask,
851    pid: pid_t,
852    cpusetsize: u32,
853    user_mask: UserAddress,
854) -> Result<usize, Errno> {
855    if pid < 0 {
856        return error!(EINVAL);
857    }
858
859    check_cpu_set_alignment(current_task, cpusetsize)?;
860
861    let weak = get_task_or_current(current_task, pid);
862    let _task = Task::from_weak(&weak)?;
863
864    // sched_setaffinity() is not implemented. Fake affinity mask based on the number of CPUs.
865    let mask = get_default_cpu_set();
866    let mask_size = std::cmp::min(cpusetsize as usize, CPU_SET_SIZE);
867    current_task.write_memory(user_mask, &mask.bits[..mask_size])?;
868    track_stub!(TODO("https://fxbug.dev/322874659"), "sched_getaffinity");
869    Ok(mask_size)
870}
871
872pub fn sys_sched_setaffinity(
873    _locked: &mut Locked<Unlocked>,
874    current_task: &CurrentTask,
875    pid: pid_t,
876    cpusetsize: u32,
877    user_mask: UserAddress,
878) -> Result<(), Errno> {
879    if pid < 0 {
880        return error!(EINVAL);
881    }
882    let weak = get_task_or_current(current_task, pid);
883    let target_task = Task::from_weak(&weak)?;
884
885    check_cpu_set_alignment(current_task, cpusetsize)?;
886
887    let mask_size = std::cmp::min(cpusetsize as usize, CPU_SET_SIZE);
888    let mut mask = CpuSet::default();
889    current_task.read_memory_to_slice(user_mask, &mut mask.bits[..mask_size])?;
890
891    // Specified mask must include at least one valid CPU.
892    let max_mask = get_default_cpu_set();
893    let mut has_valid_cpu_in_mask = false;
894    for (l1, l2) in std::iter::zip(max_mask.bits, mask.bits) {
895        has_valid_cpu_in_mask = has_valid_cpu_in_mask || (l1 & l2 > 0);
896    }
897    if !has_valid_cpu_in_mask {
898        return error!(EINVAL);
899    }
900
901    if !current_task.is_euid_friendly_with(&target_task) {
902        security::check_task_capable(current_task, CAP_SYS_NICE)?;
903    }
904
905    // Currently, we ignore the mask and act as if the system reset the mask
906    // immediately to allowing all CPUs.
907    track_stub!(TODO("https://fxbug.dev/322874889"), "sched_setaffinity");
908    Ok(())
909}
910
911pub fn sys_sched_getparam(
912    _locked: &mut Locked<Unlocked>,
913    current_task: &CurrentTask,
914    pid: pid_t,
915    param: UserRef<sched_param>,
916) -> Result<(), Errno> {
917    if pid < 0 || param.is_null() {
918        return error!(EINVAL);
919    }
920
921    let weak = get_task_or_current(current_task, pid);
922    let target_task = Task::from_weak(&weak)?;
923    let param_value = target_task.read().scheduler_state.get_sched_param();
924    current_task.write_object(param, &param_value)?;
925    Ok(())
926}
927
928pub fn sys_sched_setparam(
929    locked: &mut Locked<Unlocked>,
930    current_task: &CurrentTask,
931    pid: pid_t,
932    param: UserRef<sched_param>,
933) -> Result<(), Errno> {
934    // Parse & validate the arguments.
935    if pid < 0 || param.is_null() {
936        return error!(EINVAL);
937    }
938    let weak = get_task_or_current(current_task, pid);
939    let target_task = Task::from_weak(&weak)?;
940
941    // TODO: https://fxbug.dev/425143440 - we probably want to improve the locking here.
942    let current_state = target_task.read().scheduler_state;
943
944    let realtime_priority = current_state
945        .policy
946        .realtime_priority_from(current_task.read_object(param)?.sched_priority)?;
947
948    // Check capabilities and permissions, if required, for the operation.
949    let euid_friendly = current_task.is_euid_friendly_with(&target_task);
950    let strengthening = current_state.realtime_priority < realtime_priority;
951    let rlimited = strengthening
952        && realtime_priority
953            .exceeds(target_task.thread_group().get_rlimit(locked, Resource::RTPRIO));
954    if !euid_friendly || rlimited {
955        security::check_task_capable(current_task, CAP_SYS_NICE)?;
956    }
957
958    security::check_setsched_access(current_task, &target_task)?;
959
960    // Apply the new scheduler configuration to the task.
961    target_task.set_scheduler_priority(realtime_priority)?;
962
963    Ok(())
964}
965
966pub fn sys_sched_get_priority_min(
967    _locked: &mut Locked<Unlocked>,
968    _ctx: &CurrentTask,
969    policy: u32,
970) -> Result<u8, Errno> {
971    min_priority_for_sched_policy(policy)
972}
973
974pub fn sys_sched_get_priority_max(
975    _locked: &mut Locked<Unlocked>,
976    _ctx: &CurrentTask,
977    policy: u32,
978) -> Result<u8, Errno> {
979    max_priority_for_sched_policy(policy)
980}
981
982pub fn sys_ioprio_set(
983    _locked: &mut Locked<Unlocked>,
984    _current_task: &mut CurrentTask,
985    _which: i32,
986    _who: i32,
987    _ioprio: i32,
988) -> Result<(), Errno> {
989    track_stub!(TODO("https://fxbug.dev/297591758"), "ioprio_set()");
990    error!(ENOSYS)
991}
992
993pub fn sys_prctl(
994    locked: &mut Locked<Unlocked>,
995    current_task: &mut CurrentTask,
996    option: u32,
997    arg2: u64,
998    arg3: u64,
999    arg4: u64,
1000    arg5: u64,
1001) -> Result<SyscallResult, Errno> {
1002    match option {
1003        PR_SET_VMA => {
1004            if arg2 != PR_SET_VMA_ANON_NAME as u64 {
1005                track_stub!(TODO("https://fxbug.dev/322874826"), "prctl PR_SET_VMA", arg2);
1006                return error!(ENOSYS);
1007            }
1008            let addr = UserAddress::from(arg3);
1009            let length = arg4 as usize;
1010            let name_addr = UserAddress::from(arg5);
1011            let name = if name_addr.is_null() {
1012                None
1013            } else {
1014                let name = UserCString::new(current_task, UserAddress::from(arg5));
1015                let name = current_task.read_c_string_to_vec(name, 256).map_err(|e| {
1016                    // An overly long name produces EINVAL and not ENAMETOOLONG in Linux 5.15.
1017                    if e.code == ENAMETOOLONG { errno!(EINVAL) } else { e }
1018                })?;
1019                // Some characters are forbidden in VMA names.
1020                if name.iter().any(|b| {
1021                    matches!(b,
1022                        0..=0x1f |
1023                        0x7f..=0xff |
1024                        b'\\' | b'`' | b'$' | b'[' | b']'
1025                    )
1026                }) {
1027                    return error!(EINVAL);
1028                }
1029                Some(name)
1030            };
1031            current_task.mm()?.set_mapping_name(addr, length, name)?;
1032            Ok(().into())
1033        }
1034        PR_SET_DUMPABLE => {
1035            let mm = current_task.mm()?;
1036            let mut dumpable = mm.dumpable.lock(locked);
1037            *dumpable = if arg2 == 1 { DumpPolicy::User } else { DumpPolicy::Disable };
1038            Ok(().into())
1039        }
1040        PR_GET_DUMPABLE => {
1041            let mm = current_task.mm()?;
1042            let dumpable = mm.dumpable.lock(locked);
1043            Ok(match *dumpable {
1044                DumpPolicy::Disable => 0.into(),
1045                DumpPolicy::User => 1.into(),
1046            })
1047        }
1048        PR_SET_PDEATHSIG => {
1049            track_stub!(TODO("https://fxbug.dev/322874397"), "PR_SET_PDEATHSIG");
1050            Ok(().into())
1051        }
1052        PR_SET_NAME => {
1053            let addr = UserAddress::from(arg2);
1054            let name = TaskCommand::new(&current_task.read_memory_to_array::<16>(addr)?);
1055            current_task.set_command_name(name);
1056            Ok(0.into())
1057        }
1058        PR_GET_NAME => {
1059            let addr = UserAddress::from(arg2);
1060            let name = current_task.command().prctl_name();
1061            current_task.write_memory(addr, &name[..])?;
1062            Ok(().into())
1063        }
1064        PR_SET_PTRACER => {
1065            let allowed_ptracers = if arg2 == PR_SET_PTRACER_ANY as u64 {
1066                PtraceAllowedPtracers::Any
1067            } else if arg2 == 0 {
1068                PtraceAllowedPtracers::None
1069            } else {
1070                if current_task.kernel().pids.read().get_task(arg2 as i32).upgrade().is_none() {
1071                    return error!(EINVAL);
1072                }
1073                PtraceAllowedPtracers::Some(arg2 as pid_t)
1074            };
1075            current_task.thread_group().write().allowed_ptracers = allowed_ptracers;
1076            Ok(().into())
1077        }
1078        PR_GET_KEEPCAPS => {
1079            Ok(current_task.current_creds().securebits.contains(SecureBits::KEEP_CAPS).into())
1080        }
1081        PR_SET_KEEPCAPS => {
1082            if arg2 != 0 && arg2 != 1 {
1083                return error!(EINVAL);
1084            }
1085            let mut creds = Credentials::clone(&current_task.current_creds());
1086            creds.securebits.set(SecureBits::KEEP_CAPS, arg2 != 0);
1087            current_task.set_creds(creds);
1088            Ok(().into())
1089        }
1090        PR_SET_NO_NEW_PRIVS => {
1091            // If any args are set other than arg2 to 1, this should return einval
1092            if arg2 != 1 || arg3 != 0 || arg4 != 0 || arg5 != 0 {
1093                return error!(EINVAL);
1094            }
1095            current_task.write().enable_no_new_privs();
1096            Ok(().into())
1097        }
1098        PR_GET_NO_NEW_PRIVS => {
1099            // If any args are set, this should return einval
1100            if arg2 != 0 || arg3 != 0 || arg4 != 0 {
1101                return error!(EINVAL);
1102            }
1103            Ok(current_task.read().no_new_privs().into())
1104        }
1105        PR_GET_SECCOMP => {
1106            if current_task.seccomp_filter_state.get() == SeccompStateValue::None {
1107                Ok(0.into())
1108            } else {
1109                Ok(2.into())
1110            }
1111        }
1112        PR_SET_SECCOMP => {
1113            if arg2 == SECCOMP_MODE_STRICT as u64 {
1114                return sys_seccomp(
1115                    locked,
1116                    current_task,
1117                    SECCOMP_SET_MODE_STRICT,
1118                    0,
1119                    UserAddress::NULL,
1120                );
1121            } else if arg2 == SECCOMP_MODE_FILTER as u64 {
1122                return sys_seccomp(locked, current_task, SECCOMP_SET_MODE_FILTER, 0, arg3.into());
1123            }
1124            Ok(().into())
1125        }
1126        PR_GET_CHILD_SUBREAPER => {
1127            let addr = UserAddress::from(arg2);
1128            #[allow(clippy::bool_to_int_with_if)]
1129            let value: i32 =
1130                if current_task.thread_group().read().is_child_subreaper { 1 } else { 0 };
1131            current_task.write_object(addr.into(), &value)?;
1132            Ok(().into())
1133        }
1134        PR_SET_CHILD_SUBREAPER => {
1135            current_task.thread_group().write().is_child_subreaper = arg2 != 0;
1136            Ok(().into())
1137        }
1138        PR_GET_SECUREBITS => Ok(current_task.current_creds().securebits.bits().into()),
1139        PR_SET_SECUREBITS => {
1140            // TODO(security): This does not yet respect locked flags.
1141            let mut creds = Credentials::clone(&current_task.current_creds());
1142            security::check_task_capable(current_task, CAP_SETPCAP)?;
1143
1144            let securebits = SecureBits::from_bits(arg2 as u32).ok_or_else(|| {
1145                track_stub!(TODO("https://fxbug.dev/322875244"), "PR_SET_SECUREBITS", arg2);
1146                errno!(ENOSYS)
1147            })?;
1148            creds.securebits = securebits;
1149            current_task.set_creds(creds);
1150            Ok(().into())
1151        }
1152        PR_CAPBSET_READ => {
1153            let cap = Capabilities::try_from(arg2)?;
1154            Ok(current_task.current_creds().cap_bounding.contains(cap).into())
1155        }
1156        PR_CAPBSET_DROP => {
1157            let mut creds = Credentials::clone(&current_task.current_creds());
1158            security::check_task_capable(current_task, CAP_SETPCAP)?;
1159
1160            creds.cap_bounding.remove(Capabilities::try_from(arg2)?);
1161            current_task.set_creds(creds);
1162            Ok(().into())
1163        }
1164        PR_CAP_AMBIENT => {
1165            let operation = arg2 as u32;
1166            let capability_arg = Capabilities::try_from(arg3)?;
1167            if arg4 != 0 || arg5 != 0 {
1168                return error!(EINVAL);
1169            }
1170
1171            // TODO(security): We don't currently validate capabilities, but this should return an
1172            // error if the capability_arg is invalid.
1173            match operation {
1174                PR_CAP_AMBIENT_RAISE => {
1175                    let mut creds = Credentials::clone(&current_task.current_creds());
1176                    if !(creds.cap_permitted.contains(capability_arg)
1177                        && creds.cap_inheritable.contains(capability_arg))
1178                    {
1179                        return error!(EPERM);
1180                    }
1181                    if creds.securebits.contains(SecureBits::NO_CAP_AMBIENT_RAISE)
1182                        || creds.securebits.contains(SecureBits::NO_CAP_AMBIENT_RAISE_LOCKED)
1183                    {
1184                        return error!(EPERM);
1185                    }
1186
1187                    creds.cap_ambient.insert(capability_arg);
1188                    current_task.set_creds(creds);
1189                    Ok(().into())
1190                }
1191                PR_CAP_AMBIENT_LOWER => {
1192                    let mut creds = Credentials::clone(&current_task.current_creds());
1193                    creds.cap_ambient.remove(capability_arg);
1194                    current_task.set_creds(creds);
1195                    Ok(().into())
1196                }
1197                PR_CAP_AMBIENT_IS_SET => {
1198                    Ok(current_task.current_creds().cap_ambient.contains(capability_arg).into())
1199                }
1200                PR_CAP_AMBIENT_CLEAR_ALL => {
1201                    if arg3 != 0 {
1202                        return error!(EINVAL);
1203                    }
1204
1205                    let mut creds = Credentials::clone(&current_task.current_creds());
1206                    creds.cap_ambient = Capabilities::empty();
1207                    current_task.set_creds(creds);
1208                    Ok(().into())
1209                }
1210                _ => error!(EINVAL),
1211            }
1212        }
1213        PR_SET_TIMERSLACK => {
1214            current_task.write().set_timerslack_ns(arg2);
1215            Ok(().into())
1216        }
1217        #[cfg(target_arch = "aarch64")]
1218        PR_GET_TAGGED_ADDR_CTRL => {
1219            track_stub!(TODO("https://fxbug.dev/408554469"), "PR_GET_TAGGED_ADDR_CTRL");
1220            Ok(0.into())
1221        }
1222        #[cfg(target_arch = "aarch64")]
1223        PR_SET_TAGGED_ADDR_CTRL => match u32::try_from(arg2).map_err(|_| errno!(EINVAL))? {
1224            // Only untagged pointers are allowed, the default.
1225            0 => Ok(().into()),
1226            PR_TAGGED_ADDR_ENABLE => {
1227                track_stub!(TODO("https://fxbug.dev/408554469"), "PR_TAGGED_ADDR_ENABLE");
1228                error!(EINVAL)
1229            }
1230            unknown_mode => {
1231                track_stub!(
1232                    TODO("https://fxbug.dev/408554469"),
1233                    "PR_SET_TAGGED_ADDR_CTRL unknown mode",
1234                    unknown_mode,
1235                );
1236                error!(EINVAL)
1237            }
1238        },
1239        _ => {
1240            track_stub!(TODO("https://fxbug.dev/322874733"), "prctl fallthrough", option);
1241            error!(ENOSYS)
1242        }
1243    }
1244}
1245
1246pub fn sys_ptrace(
1247    locked: &mut Locked<Unlocked>,
1248    current_task: &mut CurrentTask,
1249    request: u32,
1250    pid: pid_t,
1251    addr: UserAddress,
1252    data: UserAddress,
1253) -> Result<SyscallResult, Errno> {
1254    match request {
1255        PTRACE_TRACEME => ptrace_traceme(current_task),
1256        PTRACE_ATTACH => ptrace_attach(locked, current_task, pid, PtraceAttachType::Attach, data),
1257        PTRACE_SEIZE => ptrace_attach(locked, current_task, pid, PtraceAttachType::Seize, data),
1258        _ => ptrace_dispatch(locked, current_task, request, pid, addr, data),
1259    }
1260}
1261
1262pub fn sys_set_tid_address(
1263    _locked: &mut Locked<Unlocked>,
1264    current_task: &CurrentTask,
1265    user_tid: UserRef<pid_t>,
1266) -> Result<pid_t, Errno> {
1267    current_task.write().clear_child_tid = user_tid;
1268    Ok(current_task.get_tid())
1269}
1270
1271pub fn sys_getrusage(
1272    _locked: &mut Locked<Unlocked>,
1273    current_task: &CurrentTask,
1274    who: i32,
1275    user_usage: RUsagePtr,
1276) -> Result<(), Errno> {
1277    const RUSAGE_SELF: i32 = starnix_uapi::uapi::RUSAGE_SELF as i32;
1278    const RUSAGE_THREAD: i32 = starnix_uapi::uapi::RUSAGE_THREAD as i32;
1279    track_stub!(TODO("https://fxbug.dev/297370242"), "real rusage");
1280    let time_stats = match who {
1281        RUSAGE_CHILDREN => current_task.task.thread_group().read().children_time_stats,
1282        RUSAGE_SELF => current_task.task.thread_group().time_stats(),
1283        RUSAGE_THREAD => current_task.task.time_stats(),
1284        _ => return error!(EINVAL),
1285    };
1286
1287    let usage = rusage {
1288        ru_utime: timeval_from_duration(time_stats.user_time),
1289        ru_stime: timeval_from_duration(time_stats.system_time),
1290        ..rusage::default()
1291    };
1292    current_task.write_multi_arch_object(user_usage, usage)?;
1293
1294    Ok(())
1295}
1296
1297type PrLimitRef = MultiArchUserRef<uapi::rlimit, uapi::arch32::rlimit>;
1298
1299pub fn sys_getrlimit(
1300    locked: &mut Locked<Unlocked>,
1301    current_task: &CurrentTask,
1302    resource: u32,
1303    user_rlimit: PrLimitRef,
1304) -> Result<(), Errno> {
1305    do_prlimit64(locked, current_task, 0, resource, PrLimitRef::null(current_task), user_rlimit)
1306}
1307
1308pub fn sys_setrlimit(
1309    locked: &mut Locked<Unlocked>,
1310    current_task: &CurrentTask,
1311    resource: u32,
1312    user_rlimit: PrLimitRef,
1313) -> Result<(), Errno> {
1314    do_prlimit64(locked, current_task, 0, resource, user_rlimit, PrLimitRef::null(current_task))
1315}
1316
1317pub fn sys_prlimit64(
1318    locked: &mut Locked<Unlocked>,
1319    current_task: &CurrentTask,
1320    pid: pid_t,
1321    user_resource: u32,
1322    new_limit_ref: UserRef<uapi::rlimit>,
1323    old_limit_ref: UserRef<uapi::rlimit>,
1324) -> Result<(), Errno> {
1325    do_prlimit64::<uapi::rlimit>(
1326        locked,
1327        current_task,
1328        pid,
1329        user_resource,
1330        new_limit_ref.into(),
1331        old_limit_ref.into(),
1332    )
1333}
1334
1335pub fn do_prlimit64<T>(
1336    locked: &mut Locked<Unlocked>,
1337    current_task: &CurrentTask,
1338    pid: pid_t,
1339    user_resource: u32,
1340    new_limit_ref: MultiArchUserRef<uapi::rlimit, T>,
1341    old_limit_ref: MultiArchUserRef<uapi::rlimit, T>,
1342) -> Result<(), Errno>
1343where
1344    T: FromBytes + IntoBytes + Immutable + From<uapi::rlimit> + Into<uapi::rlimit>,
1345{
1346    let weak = get_task_or_current(current_task, pid);
1347    let target_task = Task::from_weak(&weak)?;
1348
1349    // To get or set the resource of a process other than itself, the caller must have either:
1350    // * the same `uid`, `euid`, `saved_uid`, `gid`, `egid`, `saved_gid` as the target.
1351    // * the CAP_SYS_RESOURCE
1352    if current_task.get_pid() != target_task.get_pid() {
1353        let self_creds = current_task.current_creds();
1354        let target_creds = target_task.real_creds();
1355        if self_creds.uid != target_creds.uid
1356            || self_creds.euid != target_creds.euid
1357            || self_creds.saved_uid != target_creds.saved_uid
1358            || self_creds.gid != target_creds.gid
1359            || self_creds.egid != target_creds.egid
1360            || self_creds.saved_gid != target_creds.saved_gid
1361        {
1362            security::check_task_capable(current_task, CAP_SYS_RESOURCE)?;
1363        }
1364        security::task_prlimit(
1365            current_task,
1366            &target_task,
1367            !old_limit_ref.is_null(),
1368            !new_limit_ref.is_null(),
1369        )?;
1370    }
1371
1372    let resource = Resource::from_raw(user_resource)?;
1373
1374    let old_limit = match resource {
1375        // TODO: Integrate Resource::STACK with generic ResourceLimits machinery.
1376        Resource::STACK => {
1377            if !new_limit_ref.is_null() {
1378                track_stub!(
1379                    TODO("https://fxbug.dev/322874791"),
1380                    "prlimit64 cannot set RLIMIT_STACK"
1381                );
1382            }
1383            // The stack size is fixed at the moment, but
1384            // if MAP_GROWSDOWN is implemented this should
1385            // report the limit that it can be grown.
1386            let mm = target_task.mm()?;
1387            let mm_state = mm.state.read();
1388            let stack_size = mm_state.stack_size as u64;
1389            rlimit { rlim_cur: stack_size, rlim_max: stack_size }
1390        }
1391        _ => {
1392            let new_limit = if new_limit_ref.is_null() {
1393                None
1394            } else {
1395                let new_limit = current_task.read_multi_arch_object(new_limit_ref)?;
1396                if new_limit.rlim_cur > new_limit.rlim_max {
1397                    return error!(EINVAL);
1398                }
1399                Some(new_limit)
1400            };
1401            ThreadGroup::adjust_rlimits(locked, current_task, &target_task, resource, new_limit)?
1402        }
1403    };
1404    if !old_limit_ref.is_null() {
1405        current_task.write_multi_arch_object(old_limit_ref, old_limit)?;
1406    }
1407    Ok(())
1408}
1409
1410pub fn sys_quotactl(
1411    _locked: &mut Locked<Unlocked>,
1412    _current_task: &CurrentTask,
1413    _cmd: i32,
1414    _special: UserRef<c_char>,
1415    _id: i32,
1416    _addr: UserRef<c_char>,
1417) -> Result<SyscallResult, Errno> {
1418    track_stub!(TODO("https://fxbug.dev/297302197"), "quotacl()");
1419    error!(ENOSYS)
1420}
1421
1422pub fn sys_capget(
1423    _locked: &mut Locked<Unlocked>,
1424    current_task: &CurrentTask,
1425    user_header: UserRef<__user_cap_header_struct>,
1426    user_data: UserRef<__user_cap_data_struct>,
1427) -> Result<(), Errno> {
1428    let mut header = current_task.read_object(user_header)?;
1429    let is_version_valid =
1430        [_LINUX_CAPABILITY_VERSION_1, _LINUX_CAPABILITY_VERSION_2, _LINUX_CAPABILITY_VERSION_3]
1431            .contains(&header.version);
1432    if !is_version_valid {
1433        header.version = _LINUX_CAPABILITY_VERSION_3;
1434        current_task.write_object(user_header, &header)?;
1435    }
1436    if user_data.is_null() {
1437        return Ok(());
1438    }
1439    if !is_version_valid || header.pid < 0 {
1440        return error!(EINVAL);
1441    }
1442
1443    let weak = get_task_or_current(current_task, header.pid);
1444    let target_task = Task::from_weak(&weak)?;
1445
1446    security::check_getcap_access(current_task, &target_task)?;
1447
1448    let (permitted, effective, inheritable) = {
1449        let creds = &target_task.real_creds();
1450        (creds.cap_permitted, creds.cap_effective, creds.cap_inheritable)
1451    };
1452
1453    match header.version {
1454        _LINUX_CAPABILITY_VERSION_1 => {
1455            let data: [__user_cap_data_struct; 1] = [__user_cap_data_struct {
1456                effective: effective.as_abi_v1(),
1457                inheritable: inheritable.as_abi_v1(),
1458                permitted: permitted.as_abi_v1(),
1459            }];
1460            current_task.write_objects(user_data, &data)?;
1461        }
1462        _LINUX_CAPABILITY_VERSION_2 | _LINUX_CAPABILITY_VERSION_3 => {
1463            // Return 64 bit capabilities as two sets of 32 bit capabilities, little endian
1464            let (permitted, effective, inheritable) =
1465                (permitted.as_abi_v3(), effective.as_abi_v3(), inheritable.as_abi_v3());
1466            let data: [__user_cap_data_struct; 2] = [
1467                __user_cap_data_struct {
1468                    effective: effective.0,
1469                    inheritable: inheritable.0,
1470                    permitted: permitted.0,
1471                },
1472                __user_cap_data_struct {
1473                    effective: effective.1,
1474                    inheritable: inheritable.1,
1475                    permitted: permitted.1,
1476                },
1477            ];
1478            current_task.write_objects(user_data, &data)?;
1479        }
1480        _ => {
1481            unreachable!("already returned if Linux capability version is not valid")
1482        }
1483    }
1484    Ok(())
1485}
1486
1487pub fn sys_capset(
1488    _locked: &mut Locked<Unlocked>,
1489    current_task: &CurrentTask,
1490    user_header: UserRef<__user_cap_header_struct>,
1491    user_data: UserRef<__user_cap_data_struct>,
1492) -> Result<(), Errno> {
1493    let mut header = current_task.read_object(user_header)?;
1494    let is_version_valid =
1495        [_LINUX_CAPABILITY_VERSION_1, _LINUX_CAPABILITY_VERSION_2, _LINUX_CAPABILITY_VERSION_3]
1496            .contains(&header.version);
1497    if !is_version_valid {
1498        header.version = _LINUX_CAPABILITY_VERSION_3;
1499        current_task.write_object(user_header, &header)?;
1500        return error!(EINVAL);
1501    }
1502    if header.pid != 0 && header.pid != current_task.tid {
1503        return error!(EPERM);
1504    }
1505
1506    let (new_permitted, new_effective, new_inheritable) = match header.version {
1507        _LINUX_CAPABILITY_VERSION_1 => {
1508            let data = current_task.read_object(user_data)?;
1509            (
1510                Capabilities::from_abi_v1(data.permitted),
1511                Capabilities::from_abi_v1(data.effective),
1512                Capabilities::from_abi_v1(data.inheritable),
1513            )
1514        }
1515        _LINUX_CAPABILITY_VERSION_2 | _LINUX_CAPABILITY_VERSION_3 => {
1516            let data =
1517                current_task.read_objects_to_array::<__user_cap_data_struct, 2>(user_data)?;
1518            (
1519                Capabilities::from_abi_v3((data[0].permitted, data[1].permitted)),
1520                Capabilities::from_abi_v3((data[0].effective, data[1].effective)),
1521                Capabilities::from_abi_v3((data[0].inheritable, data[1].inheritable)),
1522            )
1523        }
1524        _ => {
1525            unreachable!("already returned if Linux capability version is not valid")
1526        }
1527    };
1528
1529    // Permission checks. Copied out of TLPI section 39.7.
1530    let mut creds = Credentials::clone(&current_task.current_creds());
1531    {
1532        log_trace!(
1533            "Capabilities({{permitted={:?} from {:?}, effective={:?} from {:?}, inheritable={:?} from {:?}}}, bounding={:?})",
1534            new_permitted,
1535            creds.cap_permitted,
1536            new_effective,
1537            creds.cap_effective,
1538            new_inheritable,
1539            creds.cap_inheritable,
1540            creds.cap_bounding
1541        );
1542        if !creds.cap_inheritable.union(creds.cap_permitted).contains(new_inheritable) {
1543            security::check_task_capable(current_task, CAP_SETPCAP)?;
1544        }
1545
1546        if !creds.cap_inheritable.union(creds.cap_bounding).contains(new_inheritable) {
1547            return error!(EPERM);
1548        }
1549        if !creds.cap_permitted.contains(new_permitted) {
1550            return error!(EPERM);
1551        }
1552        if !new_permitted.contains(new_effective) {
1553            return error!(EPERM);
1554        }
1555    }
1556    let weak = get_task_or_current(current_task, header.pid);
1557    let target_task = Task::from_weak(&weak)?;
1558
1559    security::check_setcap_access(current_task, &target_task)?;
1560
1561    creds.cap_permitted = new_permitted;
1562    creds.cap_effective = new_effective;
1563    creds.cap_inheritable = new_inheritable;
1564    creds.cap_ambient = new_permitted & new_inheritable & creds.cap_ambient;
1565    current_task.set_creds(creds);
1566    Ok(())
1567}
1568
1569pub fn sys_seccomp(
1570    locked: &mut Locked<Unlocked>,
1571    current_task: &mut CurrentTask,
1572    operation: u32,
1573    flags: u32,
1574    args: UserAddress,
1575) -> Result<SyscallResult, Errno> {
1576    match operation {
1577        SECCOMP_SET_MODE_STRICT => {
1578            if flags != 0 || args != UserAddress::NULL {
1579                return error!(EINVAL);
1580            }
1581            current_task.set_seccomp_state(SeccompStateValue::Strict)?;
1582            Ok(().into())
1583        }
1584        SECCOMP_SET_MODE_FILTER => {
1585            if flags
1586                & (SECCOMP_FILTER_FLAG_LOG
1587                    | SECCOMP_FILTER_FLAG_NEW_LISTENER
1588                    | SECCOMP_FILTER_FLAG_SPEC_ALLOW
1589                    | SECCOMP_FILTER_FLAG_TSYNC
1590                    | SECCOMP_FILTER_FLAG_TSYNC_ESRCH)
1591                != flags
1592            {
1593                return error!(EINVAL);
1594            }
1595            if (flags & SECCOMP_FILTER_FLAG_NEW_LISTENER != 0)
1596                && (flags & SECCOMP_FILTER_FLAG_TSYNC != 0)
1597                && (flags & SECCOMP_FILTER_FLAG_TSYNC_ESRCH == 0)
1598            {
1599                return error!(EINVAL);
1600            }
1601            let fprog =
1602                current_task.read_multi_arch_object(SockFProgPtr::new(current_task, args))?;
1603            if fprog.len > BPF_MAXINSNS || fprog.len == 0 {
1604                return error!(EINVAL);
1605            }
1606            let code: Vec<sock_filter> =
1607                current_task.read_multi_arch_objects_to_vec(fprog.filter, fprog.len as usize)?;
1608
1609            if !current_task.read().no_new_privs() {
1610                security::check_task_capable(current_task, CAP_SYS_ADMIN)
1611                    .map_err(|_| errno!(EACCES))?;
1612            }
1613            current_task.add_seccomp_filter(locked, code, flags)
1614        }
1615        SECCOMP_GET_ACTION_AVAIL => {
1616            if flags != 0 || args.is_null() {
1617                return error!(EINVAL);
1618            }
1619            let action: u32 = current_task.read_object(UserRef::new(args))?;
1620            SeccompAction::is_action_available(action)
1621        }
1622        SECCOMP_GET_NOTIF_SIZES => {
1623            if flags != 0 {
1624                return error!(EINVAL);
1625            }
1626            track_stub!(TODO("https://fxbug.dev/322874791"), "SECCOMP_GET_NOTIF_SIZES");
1627            error!(ENOSYS)
1628        }
1629        _ => {
1630            track_stub!(TODO("https://fxbug.dev/322874916"), "seccomp fallthrough", operation);
1631            error!(EINVAL)
1632        }
1633    }
1634}
1635
1636pub fn sys_setgroups(
1637    _locked: &mut Locked<Unlocked>,
1638    current_task: &CurrentTask,
1639    size: usize,
1640    groups_addr: UserAddress,
1641) -> Result<(), Errno> {
1642    if size > NGROUPS_MAX as usize {
1643        return error!(EINVAL);
1644    }
1645    let groups = current_task.read_objects_to_vec::<gid_t>(groups_addr.into(), size)?;
1646    let mut creds = Credentials::clone(&current_task.current_creds());
1647    if !creds.is_superuser() {
1648        return error!(EPERM);
1649    }
1650    creds.groups = groups;
1651    current_task.set_creds(creds);
1652    Ok(())
1653}
1654
1655pub fn sys_getgroups(
1656    _locked: &mut Locked<Unlocked>,
1657    current_task: &CurrentTask,
1658    size: usize,
1659    groups_addr: UserAddress,
1660) -> Result<usize, Errno> {
1661    if size > NGROUPS_MAX as usize {
1662        return error!(EINVAL);
1663    }
1664    let creds = current_task.current_creds();
1665    if size != 0 {
1666        if size < creds.groups.len() {
1667            return error!(EINVAL);
1668        }
1669        current_task.write_memory(groups_addr, creds.groups.as_slice().as_bytes())?;
1670    }
1671    Ok(creds.groups.len())
1672}
1673
1674pub fn sys_setsid(
1675    locked: &mut Locked<Unlocked>,
1676    current_task: &CurrentTask,
1677) -> Result<pid_t, Errno> {
1678    current_task.thread_group().setsid(locked)?;
1679    Ok(current_task.get_pid())
1680}
1681
1682// Note the asymmetry with sys_setpriority: this returns "kernel nice" which ranges
1683// from 1 (weakest) to 40 (strongest). (It is part of Linux history that this syscall
1684// deals with niceness but has "priority" in its name.)
1685pub fn sys_getpriority(
1686    _locked: &mut Locked<Unlocked>,
1687    current_task: &CurrentTask,
1688    which: u32,
1689    who: i32,
1690) -> Result<u8, Errno> {
1691    match which {
1692        PRIO_PROCESS => {}
1693        // TODO: https://fxbug.dev/287121196 - support PRIO_PGRP and PRIO_USER?
1694        _ => return error!(EINVAL),
1695    }
1696    track_stub!(TODO("https://fxbug.dev/322893809"), "getpriority permissions");
1697    let weak = get_task_or_current(current_task, who);
1698    let target_task = Task::from_weak(&weak)?;
1699    let state = target_task.read();
1700    Ok(state.scheduler_state.normal_priority.raw_priority())
1701}
1702
1703// Note the asymmetry with sys_getpriority: this call's `priority` parameter is a
1704// "user nice" which ranges from -20 (strongest) to 19 (weakest) (other values can be
1705// passed and are clamped to that range and interpretation). (It is part of Linux
1706// history that this syscall deals with niceness but has "priority" in its name.)
1707pub fn sys_setpriority(
1708    locked: &mut Locked<Unlocked>,
1709    current_task: &CurrentTask,
1710    which: u32,
1711    who: i32,
1712    priority: i32,
1713) -> Result<(), Errno> {
1714    // Parse & validate the arguments.
1715    match which {
1716        PRIO_PROCESS => {}
1717        // TODO: https://fxbug.dev/287121196 - support PRIO_PGRP and PRIO_USER?
1718        _ => return error!(EINVAL),
1719    }
1720
1721    let weak = get_task_or_current(current_task, who);
1722    let target_task = Task::from_weak(&weak)?;
1723
1724    let normal_priority = NormalPriority::from_setpriority_syscall(priority);
1725
1726    // TODO: https://fxbug.dev/425143440 - we probably want to improve the locking here.
1727    let current_state = target_task.read().scheduler_state;
1728
1729    // Check capabilities and permissions, if required, for the operation.
1730    let euid_friendly = current_task.is_euid_friendly_with(&target_task);
1731    let strengthening = current_state.normal_priority < normal_priority;
1732    let rlimited = strengthening
1733        && normal_priority.exceeds(target_task.thread_group().get_rlimit(locked, Resource::NICE));
1734    if !euid_friendly {
1735        security::check_task_capable(current_task, CAP_SYS_NICE)?;
1736    } else if rlimited {
1737        security::check_task_capable(current_task, CAP_SYS_NICE).map_err(|_| errno!(EACCES))?;
1738    }
1739
1740    security::check_setsched_access(current_task, &target_task)?;
1741
1742    // Apply the new scheduler configuration to the task.
1743    target_task.set_scheduler_nice(normal_priority)?;
1744
1745    Ok(())
1746}
1747
1748pub fn sys_setns(
1749    _locked: &mut Locked<Unlocked>,
1750    current_task: &CurrentTask,
1751    ns_fd: FdNumber,
1752    ns_type: c_int,
1753) -> Result<(), Errno> {
1754    let file_handle = current_task.task.files.get(ns_fd)?;
1755
1756    // From man pages this is not quite right because some namespace types require more capabilities
1757    // or require this capability in multiple namespaces, but it should cover our current test
1758    // cases and we can make this more nuanced once more namespace types are supported.
1759    security::check_task_capable(current_task, CAP_SYS_ADMIN)?;
1760
1761    if let Some(mount_ns) = file_handle.downcast_file::<MountNamespaceFile>() {
1762        if !(ns_type == 0 || ns_type == CLONE_NEWNS as i32) {
1763            log_trace!("invalid type");
1764            return error!(EINVAL);
1765        }
1766
1767        track_stub!(TODO("https://fxbug.dev/297312091"), "setns CLONE_FS limitations");
1768        current_task.task.fs().set_namespace(mount_ns.0.clone())?;
1769        return Ok(());
1770    }
1771
1772    if let Some(_pidfd) = file_handle.downcast_file::<PidFdFileObject>() {
1773        track_stub!(TODO("https://fxbug.dev/297312844"), "setns w/ pidfd");
1774        return error!(ENOSYS);
1775    }
1776
1777    track_stub!(TODO("https://fxbug.dev/322893829"), "unknown ns file for setns, see logs");
1778    log_info!("ns_fd was not a supported namespace file: {}", file_handle.ops_type_name());
1779    error!(EINVAL)
1780}
1781
1782pub fn sys_unshare(
1783    _locked: &mut Locked<Unlocked>,
1784    current_task: &CurrentTask,
1785    flags: u32,
1786) -> Result<(), Errno> {
1787    const IMPLEMENTED_FLAGS: u32 = CLONE_FILES | CLONE_FS | CLONE_NEWNS | CLONE_NEWUTS;
1788    if flags & !IMPLEMENTED_FLAGS != 0 {
1789        track_stub!(TODO("https://fxbug.dev/322893372"), "unshare", flags & !IMPLEMENTED_FLAGS);
1790        return error!(EINVAL);
1791    }
1792
1793    if (flags & CLONE_FILES) != 0 {
1794        current_task.files.unshare();
1795    }
1796
1797    if (flags & CLONE_FS) != 0 {
1798        current_task.unshare_fs();
1799    }
1800
1801    if (flags & CLONE_NEWNS) != 0 {
1802        security::check_task_capable(current_task, CAP_SYS_ADMIN)?;
1803        current_task.fs().unshare_namespace();
1804    }
1805
1806    if (flags & CLONE_NEWUTS) != 0 {
1807        security::check_task_capable(current_task, CAP_SYS_ADMIN)?;
1808        // Fork the UTS namespace.
1809        let mut task_state = current_task.write();
1810        let new_uts_ns = task_state.uts_ns.read().clone();
1811        task_state.uts_ns = Arc::new(RwLock::new(new_uts_ns));
1812    }
1813
1814    Ok(())
1815}
1816
1817pub fn sys_swapon(
1818    locked: &mut Locked<Unlocked>,
1819    current_task: &CurrentTask,
1820    user_path: UserCString,
1821    _flags: i32,
1822) -> Result<(), Errno> {
1823    const MAX_SWAPFILES: usize = 32; // See https://man7.org/linux/man-pages/man2/swapon.2.html
1824
1825    security::check_task_capable(current_task, CAP_SYS_ADMIN)?;
1826
1827    track_stub!(TODO("https://fxbug.dev/322893905"), "swapon validate flags");
1828
1829    let path = current_task.read_path(user_path)?;
1830    let file = current_task.open_file(locked, path.as_ref(), OpenFlags::RDWR)?;
1831
1832    let node = file.node();
1833    let mode = node.info().mode;
1834    if !mode.is_reg() && !mode.is_blk() {
1835        return error!(EINVAL);
1836    }
1837
1838    // We determined this magic number by using the mkswap tool and the file tool. The mkswap tool
1839    // populates a few bytes in the file, including a UUID, which can be replaced with zeros while
1840    // still being recognized by the file tool. This string appears at a fixed offset
1841    // (MAGIC_OFFSET) in the file, which looks quite like a magic number.
1842    const MAGIC_OFFSET: usize = 0xff6;
1843    let swap_magic = b"SWAPSPACE2";
1844    let mut buffer = VecOutputBuffer::new(swap_magic.len());
1845    if file.read_at(locked, current_task, MAGIC_OFFSET, &mut buffer)? != swap_magic.len()
1846        || buffer.data() != swap_magic
1847    {
1848        return error!(EINVAL);
1849    }
1850
1851    let mut swap_files = current_task.kernel().swap_files.lock(locked);
1852    for swap_node in swap_files.iter() {
1853        if Arc::ptr_eq(swap_node, node) {
1854            return error!(EBUSY);
1855        }
1856    }
1857    if swap_files.len() >= MAX_SWAPFILES {
1858        return error!(EPERM);
1859    }
1860    swap_files.push(node.clone());
1861    Ok(())
1862}
1863
1864pub fn sys_swapoff(
1865    locked: &mut Locked<Unlocked>,
1866    current_task: &CurrentTask,
1867    user_path: UserCString,
1868) -> Result<(), Errno> {
1869    security::check_task_capable(current_task, CAP_SYS_ADMIN)?;
1870
1871    let path = current_task.read_path(user_path)?;
1872    let file = current_task.open_file(locked, path.as_ref(), OpenFlags::RDWR)?;
1873    let node = file.node();
1874
1875    let mut swap_files = current_task.kernel().swap_files.lock(locked);
1876    let original_length = swap_files.len();
1877    swap_files.retain(|swap_node| !Arc::ptr_eq(swap_node, node));
1878    if swap_files.len() == original_length {
1879        return error!(EINVAL);
1880    }
1881    Ok(())
1882}
1883
1884#[derive(Default, Debug, IntoBytes, KnownLayout, FromBytes, Immutable)]
1885#[repr(C)]
1886struct KcmpParams {
1887    mask: usize,
1888    shuffle: usize,
1889}
1890
1891static KCMP_PARAMS: LazyLock<KcmpParams> = LazyLock::new(|| {
1892    let mut params = KcmpParams::default();
1893    zx::cprng_draw(params.as_mut_bytes());
1894    // Ensure the shuffle is odd so that multiplying a usize by this value is a permutation.
1895    params.shuffle |= 1;
1896    params
1897});
1898
1899fn obfuscate_value(value: usize) -> usize {
1900    let KcmpParams { mask, shuffle } = *KCMP_PARAMS;
1901    (value ^ mask).wrapping_mul(shuffle)
1902}
1903
1904fn obfuscate_ptr<T>(ptr: *const T) -> usize {
1905    obfuscate_value(ptr as usize)
1906}
1907
1908fn obfuscate_arc<T>(arc: &Arc<T>) -> usize {
1909    obfuscate_ptr(Arc::as_ptr(arc))
1910}
1911
1912pub fn sys_kcmp(
1913    locked: &mut Locked<Unlocked>,
1914    current_task: &CurrentTask,
1915    pid1: pid_t,
1916    pid2: pid_t,
1917    resource_type: u32,
1918    index1: u64,
1919    index2: u64,
1920) -> Result<u32, Errno> {
1921    let weak1 = current_task.get_task(pid1);
1922    let weak2 = current_task.get_task(pid2);
1923    let task1 = Task::from_weak(&weak1)?;
1924    let task2 = Task::from_weak(&weak2)?;
1925
1926    current_task.check_ptrace_access_mode(locked, PTRACE_MODE_READ_REALCREDS, &task1)?;
1927    current_task.check_ptrace_access_mode(locked, PTRACE_MODE_READ_REALCREDS, &task2)?;
1928
1929    let resource_type = KcmpResource::from_raw(resource_type)?;
1930
1931    // Output encoding (see <https://man7.org/linux/man-pages/man2/kcmp.2.html>):
1932    //
1933    //   0  v1 is equal to v2; in other words, the two processes share the resource.
1934    //   1  v1 is less than v2.
1935    //   2  v1 is greater than v2.
1936    //   3  v1 is not equal to v2, but ordering information is unavailable.
1937    //
1938    fn encode_ordering(value: cmp::Ordering) -> u32 {
1939        match value {
1940            cmp::Ordering::Equal => 0,
1941            cmp::Ordering::Less => 1,
1942            cmp::Ordering::Greater => 2,
1943        }
1944    }
1945
1946    match resource_type {
1947        KcmpResource::FILE => {
1948            fn get_file(task: &Task, index: u64) -> Result<FileHandle, Errno> {
1949                // TODO: Test whether O_PATH is allowed here. Conceptually, seems like
1950                //       O_PATH should be allowed, but we haven't tested it yet.
1951                task.files.get_allowing_opath(FdNumber::from_raw(
1952                    index.try_into().map_err(|_| errno!(EBADF))?,
1953                ))
1954            }
1955            let file1 = get_file(&task1, index1)?;
1956            let file2 = get_file(&task2, index2)?;
1957            Ok(encode_ordering(obfuscate_arc(&file1).cmp(&obfuscate_arc(&file2))))
1958        }
1959        KcmpResource::FILES => Ok(encode_ordering(
1960            obfuscate_value(task1.files.id().raw()).cmp(&obfuscate_value(task2.files.id().raw())),
1961        )),
1962        KcmpResource::FS => {
1963            Ok(encode_ordering(obfuscate_arc(&task1.fs()).cmp(&obfuscate_arc(&task2.fs()))))
1964        }
1965        KcmpResource::SIGHAND => Ok(encode_ordering(
1966            obfuscate_arc(&task1.thread_group().signal_actions)
1967                .cmp(&obfuscate_arc(&task2.thread_group().signal_actions)),
1968        )),
1969        KcmpResource::VM => {
1970            Ok(encode_ordering(obfuscate_arc(&task1.mm()?).cmp(&obfuscate_arc(&task2.mm()?))))
1971        }
1972        _ => error!(EINVAL),
1973    }
1974}
1975
1976pub fn sys_syslog(
1977    locked: &mut Locked<Unlocked>,
1978    current_task: &CurrentTask,
1979    action_type: i32,
1980    address: UserAddress,
1981    length: i32,
1982) -> Result<i32, Errno> {
1983    let action = SyslogAction::try_from(action_type)?;
1984    let syslog =
1985        current_task.kernel().syslog.access(&current_task, SyslogAccess::Syscall(action))?;
1986    match action {
1987        SyslogAction::Read => {
1988            if address.is_null() || length < 0 {
1989                return error!(EINVAL);
1990            }
1991            let mut output_buffer =
1992                UserBuffersOutputBuffer::unified_new_at(current_task, address, length as usize)?;
1993            syslog.blocking_read(locked, current_task, &mut output_buffer)
1994        }
1995        SyslogAction::ReadAll => {
1996            if address.is_null() || length < 0 {
1997                return error!(EINVAL);
1998            }
1999            let mut output_buffer =
2000                UserBuffersOutputBuffer::unified_new_at(current_task, address, length as usize)?;
2001            syslog.read_all(current_task, &mut output_buffer)
2002        }
2003        SyslogAction::SizeUnread => syslog.size_unread(),
2004        SyslogAction::SizeBuffer => syslog.size_buffer(),
2005        SyslogAction::Close | SyslogAction::Open => Ok(0),
2006        SyslogAction::ReadClear => {
2007            track_stub!(TODO("https://fxbug.dev/322894145"), "syslog: read clear");
2008            Ok(0)
2009        }
2010        SyslogAction::Clear => {
2011            track_stub!(TODO("https://fxbug.dev/322893673"), "syslog: clear");
2012            Ok(0)
2013        }
2014        SyslogAction::ConsoleOff => {
2015            track_stub!(TODO("https://fxbug.dev/322894399"), "syslog: console off");
2016            Ok(0)
2017        }
2018        SyslogAction::ConsoleOn => {
2019            track_stub!(TODO("https://fxbug.dev/322894106"), "syslog: console on");
2020            Ok(0)
2021        }
2022        SyslogAction::ConsoleLevel => {
2023            if length <= 0 || length >= 8 {
2024                return error!(EINVAL);
2025            }
2026            track_stub!(TODO("https://fxbug.dev/322894199"), "syslog: console level");
2027            Ok(0)
2028        }
2029    }
2030}
2031
2032pub fn sys_vhangup(
2033    _locked: &mut Locked<Unlocked>,
2034    current_task: &CurrentTask,
2035) -> Result<(), Errno> {
2036    security::check_task_capable(current_task, CAP_SYS_TTY_CONFIG)?;
2037    track_stub!(TODO("https://fxbug.dev/324079257"), "vhangup");
2038    Ok(())
2039}
2040
2041// Syscalls for arch32 usage
2042#[cfg(target_arch = "aarch64")]
2043mod arch32 {
2044    pub use super::{
2045        sys_execve as sys_arch32_execve, sys_getegid as sys_arch32_getegid32,
2046        sys_geteuid as sys_arch32_geteuid32, sys_getgid as sys_arch32_getgid32,
2047        sys_getgroups as sys_arch32_getgroups32, sys_getpgid as sys_arch32_getpgid,
2048        sys_getppid as sys_arch32_getppid, sys_getpriority as sys_arch32_getpriority,
2049        sys_getresgid as sys_arch32_getresgid32, sys_getresuid as sys_arch32_getresuid32,
2050        sys_getrlimit as sys_arch32_ugetrlimit, sys_getrusage as sys_arch32_getrusage,
2051        sys_getuid as sys_arch32_getuid32, sys_ioprio_set as sys_arch32_ioprio_set,
2052        sys_ptrace as sys_arch32_ptrace, sys_quotactl as sys_arch32_quotactl,
2053        sys_sched_get_priority_max as sys_arch32_sched_get_priority_max,
2054        sys_sched_get_priority_min as sys_arch32_sched_get_priority_min,
2055        sys_sched_getaffinity as sys_arch32_sched_getaffinity,
2056        sys_sched_getparam as sys_arch32_sched_getparam,
2057        sys_sched_setaffinity as sys_arch32_sched_setaffinity,
2058        sys_sched_setparam as sys_arch32_sched_setparam,
2059        sys_sched_setscheduler as sys_arch32_sched_setscheduler, sys_seccomp as sys_arch32_seccomp,
2060        sys_setfsuid as sys_arch32_setfsuid, sys_setfsuid as sys_arch32_setfsuid32,
2061        sys_setgid as sys_arch32_setgid32, sys_setgroups as sys_arch32_setgroups32,
2062        sys_setns as sys_arch32_setns, sys_setpgid as sys_arch32_setpgid,
2063        sys_setpriority as sys_arch32_setpriority, sys_setregid as sys_arch32_setregid32,
2064        sys_setresgid as sys_arch32_setresgid32, sys_setresuid as sys_arch32_setresuid32,
2065        sys_setreuid as sys_arch32_setreuid32, sys_setreuid as sys_arch32_setreuid,
2066        sys_setrlimit as sys_arch32_setrlimit, sys_setsid as sys_arch32_setsid,
2067        sys_syslog as sys_arch32_syslog, sys_unshare as sys_arch32_unshare,
2068    };
2069}
2070
2071#[cfg(target_arch = "aarch64")]
2072pub use arch32::*;
2073
2074#[cfg(test)]
2075mod tests {
2076    use super::*;
2077    use crate::mm::syscalls::sys_munmap;
2078    use crate::testing::{AutoReleasableTask, map_memory, spawn_kernel_and_run};
2079    use starnix_syscalls::SUCCESS;
2080    use starnix_task_command::TaskCommand;
2081    use starnix_uapi::auth::Credentials;
2082    use starnix_uapi::{SCHED_FIFO, SCHED_NORMAL};
2083    use std::ffi::CString;
2084
2085    #[::fuchsia::test]
2086    async fn test_prctl_set_vma_anon_name() {
2087        spawn_kernel_and_run(async |locked, current_task| {
2088            let mapped_address =
2089                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2090            let name_addr = (mapped_address + 128u64).unwrap();
2091            let name = "test-name\0";
2092            current_task.write_memory(name_addr, name.as_bytes()).expect("failed to write name");
2093            sys_prctl(
2094                locked,
2095                current_task,
2096                PR_SET_VMA,
2097                PR_SET_VMA_ANON_NAME as u64,
2098                mapped_address.ptr() as u64,
2099                32,
2100                name_addr.ptr() as u64,
2101            )
2102            .expect("failed to set name");
2103            assert_eq!(
2104                "test-name",
2105                current_task
2106                    .mm()
2107                    .unwrap()
2108                    .get_mapping_name((mapped_address + 24u64).unwrap())
2109                    .expect("failed to get address")
2110                    .unwrap()
2111                    .to_string(),
2112            );
2113
2114            sys_munmap(locked, &current_task, mapped_address, *PAGE_SIZE as usize)
2115                .expect("failed to unmap memory");
2116            assert_eq!(
2117                error!(EFAULT),
2118                current_task.mm().unwrap().get_mapping_name((mapped_address + 24u64).unwrap())
2119            );
2120        })
2121        .await;
2122    }
2123
2124    #[::fuchsia::test]
2125    async fn test_set_vma_name_special_chars() {
2126        spawn_kernel_and_run(async |locked, current_task| {
2127            let name_addr = map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2128
2129            let mapping_addr =
2130                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2131
2132            for c in 1..255 {
2133                let vma_name = CString::new([c]).unwrap();
2134                current_task.write_memory(name_addr, vma_name.as_bytes_with_nul()).unwrap();
2135
2136                let result = sys_prctl(
2137                    locked,
2138                    current_task,
2139                    PR_SET_VMA,
2140                    PR_SET_VMA_ANON_NAME as u64,
2141                    mapping_addr.ptr() as u64,
2142                    *PAGE_SIZE,
2143                    name_addr.ptr() as u64,
2144                );
2145
2146                if c > 0x1f
2147                    && c < 0x7f
2148                    && c != b'\\'
2149                    && c != b'`'
2150                    && c != b'$'
2151                    && c != b'['
2152                    && c != b']'
2153                {
2154                    assert_eq!(result, Ok(SUCCESS));
2155                } else {
2156                    assert_eq!(result, error!(EINVAL));
2157                }
2158            }
2159        })
2160        .await;
2161    }
2162
2163    #[::fuchsia::test]
2164    async fn test_set_vma_name_long() {
2165        spawn_kernel_and_run(async |locked, current_task| {
2166            let name_addr = map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2167
2168            let mapping_addr =
2169                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2170
2171            let name_too_long = CString::new(vec![b'a'; 256]).unwrap();
2172
2173            current_task.write_memory(name_addr, name_too_long.as_bytes_with_nul()).unwrap();
2174
2175            assert_eq!(
2176                sys_prctl(
2177                    locked,
2178                    current_task,
2179                    PR_SET_VMA,
2180                    PR_SET_VMA_ANON_NAME as u64,
2181                    mapping_addr.ptr() as u64,
2182                    *PAGE_SIZE,
2183                    name_addr.ptr() as u64,
2184                ),
2185                error!(EINVAL)
2186            );
2187
2188            let name_just_long_enough = CString::new(vec![b'a'; 255]).unwrap();
2189
2190            current_task
2191                .write_memory(name_addr, name_just_long_enough.as_bytes_with_nul())
2192                .unwrap();
2193
2194            assert_eq!(
2195                sys_prctl(
2196                    locked,
2197                    current_task,
2198                    PR_SET_VMA,
2199                    PR_SET_VMA_ANON_NAME as u64,
2200                    mapping_addr.ptr() as u64,
2201                    *PAGE_SIZE,
2202                    name_addr.ptr() as u64,
2203                ),
2204                Ok(SUCCESS)
2205            );
2206        })
2207        .await;
2208    }
2209
2210    #[::fuchsia::test]
2211    async fn test_set_vma_name_misaligned() {
2212        spawn_kernel_and_run(async |locked, current_task| {
2213            let name_addr = map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2214
2215            let mapping_addr =
2216                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2217
2218            let name = CString::new("name").unwrap();
2219            current_task.write_memory(name_addr, name.as_bytes_with_nul()).unwrap();
2220
2221            // Passing a misaligned pointer to the start of the named region fails.
2222            assert_eq!(
2223                sys_prctl(
2224                    locked,
2225                    current_task,
2226                    PR_SET_VMA,
2227                    PR_SET_VMA_ANON_NAME as u64,
2228                    1 + mapping_addr.ptr() as u64,
2229                    *PAGE_SIZE - 1,
2230                    name_addr.ptr() as u64,
2231                ),
2232                error!(EINVAL)
2233            );
2234
2235            // Passing an unaligned length does work, however.
2236            assert_eq!(
2237                sys_prctl(
2238                    locked,
2239                    current_task,
2240                    PR_SET_VMA,
2241                    PR_SET_VMA_ANON_NAME as u64,
2242                    mapping_addr.ptr() as u64,
2243                    *PAGE_SIZE - 1,
2244                    name_addr.ptr() as u64,
2245                ),
2246                Ok(SUCCESS)
2247            );
2248        })
2249        .await;
2250    }
2251
2252    #[::fuchsia::test]
2253    async fn test_prctl_get_set_dumpable() {
2254        spawn_kernel_and_run(async |locked, current_task| {
2255            sys_prctl(locked, current_task, PR_GET_DUMPABLE, 0, 0, 0, 0)
2256                .expect("failed to get dumpable");
2257
2258            sys_prctl(locked, current_task, PR_SET_DUMPABLE, 1, 0, 0, 0)
2259                .expect("failed to set dumpable");
2260            sys_prctl(locked, current_task, PR_GET_DUMPABLE, 0, 0, 0, 0)
2261                .expect("failed to get dumpable");
2262
2263            // SUID_DUMP_ROOT not supported.
2264            sys_prctl(locked, current_task, PR_SET_DUMPABLE, 2, 0, 0, 0)
2265                .expect("failed to set dumpable");
2266            sys_prctl(locked, current_task, PR_GET_DUMPABLE, 0, 0, 0, 0)
2267                .expect("failed to get dumpable");
2268        })
2269        .await;
2270    }
2271
2272    #[::fuchsia::test]
2273    async fn test_sys_getsid() {
2274        spawn_kernel_and_run(async |locked, current_task| {
2275            let kernel = current_task.kernel();
2276            assert_eq!(
2277                current_task.get_tid(),
2278                sys_getsid(locked, &current_task, 0).expect("failed to get sid")
2279            );
2280
2281            let second_task = crate::execution::create_init_child_process(
2282                locked,
2283                &kernel.weak_self.upgrade().unwrap(),
2284                TaskCommand::new(b"second task"),
2285                Some(&CString::new("#kernel").unwrap()),
2286            )
2287            .expect("failed to create second task");
2288            second_task
2289                .mm()
2290                .unwrap()
2291                .initialize_mmap_layout_for_test(starnix_types::arch::ArchWidth::Arch64);
2292            let second_current = AutoReleasableTask::from(second_task);
2293
2294            assert_eq!(
2295                second_current.get_tid(),
2296                sys_getsid(locked, &current_task, second_current.get_tid())
2297                    .expect("failed to get sid")
2298            );
2299        })
2300        .await;
2301    }
2302
2303    #[::fuchsia::test]
2304    async fn test_get_affinity_size() {
2305        spawn_kernel_and_run(async |locked, current_task| {
2306            let mapped_address =
2307                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2308            let pid = current_task.get_pid();
2309            assert_eq!(
2310                sys_sched_getaffinity(locked, &current_task, pid, 16, mapped_address),
2311                Ok(16)
2312            );
2313            assert_eq!(
2314                sys_sched_getaffinity(locked, &current_task, pid, 1024, mapped_address),
2315                Ok(std::mem::size_of::<CpuSet>())
2316            );
2317            assert_eq!(
2318                sys_sched_getaffinity(locked, &current_task, pid, 1, mapped_address),
2319                error!(EINVAL)
2320            );
2321            assert_eq!(
2322                sys_sched_getaffinity(locked, &current_task, pid, 9, mapped_address),
2323                error!(EINVAL)
2324            );
2325        })
2326        .await;
2327    }
2328
2329    #[::fuchsia::test]
2330    async fn test_set_affinity_size() {
2331        spawn_kernel_and_run(async |locked, current_task| {
2332            let mapped_address =
2333                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2334            current_task.write_memory(mapped_address, &[0xffu8]).expect("failed to cpumask");
2335            let pid = current_task.get_pid();
2336            assert_eq!(
2337                sys_sched_setaffinity(
2338                    locked,
2339                    &current_task,
2340                    pid,
2341                    *PAGE_SIZE as u32,
2342                    mapped_address
2343                ),
2344                Ok(())
2345            );
2346            assert_eq!(
2347                sys_sched_setaffinity(locked, &current_task, pid, 1, mapped_address),
2348                error!(EINVAL)
2349            );
2350        })
2351        .await;
2352    }
2353
2354    #[::fuchsia::test]
2355    async fn test_task_name() {
2356        spawn_kernel_and_run(async |locked, current_task| {
2357            let mapped_address =
2358                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2359            let name = "my-task-name\0";
2360            current_task
2361                .write_memory(mapped_address, name.as_bytes())
2362                .expect("failed to write name");
2363
2364            let result =
2365                sys_prctl(locked, current_task, PR_SET_NAME, mapped_address.ptr() as u64, 0, 0, 0)
2366                    .unwrap();
2367            assert_eq!(SUCCESS, result);
2368
2369            let mapped_address =
2370                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2371            let result =
2372                sys_prctl(locked, current_task, PR_GET_NAME, mapped_address.ptr() as u64, 0, 0, 0)
2373                    .unwrap();
2374            assert_eq!(SUCCESS, result);
2375
2376            let name_length = name.len();
2377
2378            let out_name = current_task.read_memory_to_vec(mapped_address, name_length).unwrap();
2379            assert_eq!(name.as_bytes(), &out_name);
2380        })
2381        .await;
2382    }
2383
2384    #[::fuchsia::test]
2385    async fn test_sched_get_priority_min_max() {
2386        spawn_kernel_and_run(async |locked, current_task| {
2387            let non_rt_min =
2388                sys_sched_get_priority_min(locked, &current_task, SCHED_NORMAL).unwrap();
2389            assert_eq!(non_rt_min, 0);
2390            let non_rt_max =
2391                sys_sched_get_priority_max(locked, &current_task, SCHED_NORMAL).unwrap();
2392            assert_eq!(non_rt_max, 0);
2393
2394            let rt_min = sys_sched_get_priority_min(locked, &current_task, SCHED_FIFO).unwrap();
2395            assert_eq!(rt_min, 1);
2396            let rt_max = sys_sched_get_priority_max(locked, &current_task, SCHED_FIFO).unwrap();
2397            assert_eq!(rt_max, 99);
2398
2399            let min_bad_policy_error =
2400                sys_sched_get_priority_min(locked, &current_task, std::u32::MAX).unwrap_err();
2401            assert_eq!(min_bad_policy_error, errno!(EINVAL));
2402
2403            let max_bad_policy_error =
2404                sys_sched_get_priority_max(locked, &current_task, std::u32::MAX).unwrap_err();
2405            assert_eq!(max_bad_policy_error, errno!(EINVAL));
2406        })
2407        .await;
2408    }
2409
2410    #[::fuchsia::test]
2411    async fn test_sched_setscheduler() {
2412        spawn_kernel_and_run(async |locked, current_task| {
2413            current_task
2414                .thread_group()
2415                .limits
2416                .lock(locked)
2417                .set(Resource::RTPRIO, rlimit { rlim_cur: 255, rlim_max: 255 });
2418
2419            let scheduler = sys_sched_getscheduler(locked, &current_task, 0).unwrap();
2420            assert_eq!(scheduler, SCHED_NORMAL, "tasks should have normal scheduler by default");
2421
2422            let mapped_address =
2423                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2424            let requested_params = sched_param { sched_priority: 15 };
2425            current_task.write_object(mapped_address.into(), &requested_params).unwrap();
2426
2427            sys_sched_setscheduler(locked, &current_task, 0, SCHED_FIFO, mapped_address.into())
2428                .unwrap();
2429
2430            let new_scheduler = sys_sched_getscheduler(locked, &current_task, 0).unwrap();
2431            assert_eq!(new_scheduler, SCHED_FIFO, "task should have been assigned fifo scheduler");
2432
2433            let mapped_address =
2434                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2435            sys_sched_getparam(locked, &current_task, 0, mapped_address.into())
2436                .expect("sched_getparam");
2437            let param_value: sched_param =
2438                current_task.read_object(mapped_address.into()).expect("read_object");
2439            assert_eq!(param_value.sched_priority, 15);
2440        })
2441        .await;
2442    }
2443
2444    #[::fuchsia::test]
2445    async fn test_sched_getparam() {
2446        spawn_kernel_and_run(async |locked, current_task| {
2447            let mapped_address =
2448                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2449            sys_sched_getparam(locked, &current_task, 0, mapped_address.into())
2450                .expect("sched_getparam");
2451            let param_value: sched_param =
2452                current_task.read_object(mapped_address.into()).expect("read_object");
2453            assert_eq!(param_value.sched_priority, 0);
2454        })
2455        .await;
2456    }
2457
2458    #[::fuchsia::test]
2459    async fn test_setuid() {
2460        spawn_kernel_and_run(async |locked, current_task| {
2461            // Test for root.
2462            current_task.set_creds(Credentials::clone(&Credentials::root()));
2463            sys_setuid(locked, &current_task, 42).expect("setuid");
2464            let mut creds = Credentials::clone(&current_task.current_creds());
2465            assert_eq!(creds.euid, 42);
2466            assert_eq!(creds.uid, 42);
2467            assert_eq!(creds.saved_uid, 42);
2468
2469            // Remove the CAP_SETUID capability to avoid overwriting permission checks.
2470            creds.cap_effective.remove(CAP_SETUID);
2471            current_task.set_creds(creds);
2472
2473            // Test for non root, which task now is.
2474            assert_eq!(sys_setuid(locked, &current_task, 0), error!(EPERM));
2475            assert_eq!(sys_setuid(locked, &current_task, 43), error!(EPERM));
2476
2477            sys_setuid(locked, &current_task, 42).expect("setuid");
2478            let creds = current_task.clone_creds();
2479            assert_eq!(creds.euid, 42);
2480            assert_eq!(creds.uid, 42);
2481            assert_eq!(creds.saved_uid, 42);
2482
2483            // Change uid and saved_uid, and check that one can set the euid to these.
2484            let mut creds = Credentials::clone(&current_task.current_creds());
2485            creds.uid = 41;
2486            creds.euid = 42;
2487            creds.saved_uid = 43;
2488            current_task.set_creds(creds);
2489
2490            sys_setuid(locked, &current_task, 41).expect("setuid");
2491            let creds = current_task.clone_creds();
2492            assert_eq!(creds.euid, 41);
2493            assert_eq!(creds.uid, 41);
2494            assert_eq!(creds.saved_uid, 43);
2495
2496            let mut creds = Credentials::clone(&current_task.current_creds());
2497            creds.uid = 41;
2498            creds.euid = 42;
2499            creds.saved_uid = 43;
2500            current_task.set_creds(creds);
2501
2502            sys_setuid(locked, &current_task, 43).expect("setuid");
2503            let creds = current_task.clone_creds();
2504            assert_eq!(creds.euid, 43);
2505            assert_eq!(creds.uid, 41);
2506            assert_eq!(creds.saved_uid, 43);
2507        })
2508        .await;
2509    }
2510
2511    #[::fuchsia::test]
2512    async fn test_read_c_string_vector() {
2513        spawn_kernel_and_run(async |locked, current_task| {
2514            let arg_addr = map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE);
2515            let arg = b"test-arg\0";
2516            current_task.write_memory(arg_addr, arg).expect("failed to write test arg");
2517            let arg_usercstr = UserCString::new(current_task, arg_addr);
2518            let null_usercstr = UserCString::null(current_task);
2519
2520            let argv_addr = UserCStringPtr::new(
2521                current_task,
2522                map_memory(locked, &current_task, UserAddress::default(), *PAGE_SIZE),
2523            );
2524            current_task
2525                .write_multi_arch_ptr(argv_addr.addr(), arg_usercstr)
2526                .expect("failed to write UserCString");
2527            current_task
2528                .write_multi_arch_ptr(argv_addr.next().unwrap().addr(), null_usercstr)
2529                .expect("failed to write UserCString");
2530
2531            // The arguments size limit should include the null terminator.
2532            assert!(read_c_string_vector(&current_task, argv_addr, 100, arg.len()).is_ok());
2533            assert_eq!(
2534                read_c_string_vector(
2535                    &current_task,
2536                    argv_addr,
2537                    100,
2538                    std::str::from_utf8(arg).unwrap().trim_matches('\0').len()
2539                ),
2540                error!(E2BIG)
2541            );
2542        })
2543        .await;
2544    }
2545}