//
// Syd: rock-solid application kernel
// src/kernel/uname.rs: uname(2) handler
//
// Copyright (c) 2023, 2024, 2025 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY: This module has been liberated from unsafe code!
#![forbid(unsafe_code)]

use libseccomp::ScmpNotifResp;
use nix::errno::Errno;

use crate::{confine::is_valid_ptr, cookie::safe_uname, req::UNotifyEventRequest};

pub(crate) fn sys_uname(request: UNotifyEventRequest) -> ScmpNotifResp {
    syscall_handler!(request, |request: UNotifyEventRequest| {
        let req = request.scmpreq;

        // SAFETY: Check pointer against mmap_min_addr.
        let ptr = if !is_valid_ptr(req.data.args[0], req.data.arch) {
            return Err(Errno::EFAULT);
        } else {
            req.data.args[0]
        };

        // Read UtsName using uname(2) syscall.
        //
        // SAFETY: Syscall is confined with syscall argument cookies.
        let mut utsname = safe_uname()?;

        // Mask utsname using the sandbox.
        let sandbox = request.get_sandbox();
        sandbox.mask_uname(&mut utsname);
        drop(sandbox); // release the read-lock.

        // Write structure to sandbox process memory.
        request.write_mem(utsname.as_bytes(), ptr)?;

        // All good, return success.
        Ok(request.return_syscall(0))
    })
}
