//
// Syd: rock-solid application kernel
// src/kernel/sys_ptrace.rs: ptrace(2) handler
//
// Copyright (c) 2025, 2026 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::req::UNotifyEventRequest;

const PTRACE_TRACEME: u64 = libc::PTRACE_TRACEME as u64;

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

        // We only hook into PTRACE_TRACEME requests.
        assert_eq!(req.data.args[0], PTRACE_TRACEME);

        let res = request.add_ptrace(req.pid());
        match res {
            // ECANCELED which will result in a no-op.
            Ok(_) => Err(Errno::ECANCELED),
            Err(errno) => Err(errno),
        }
    })
}
