package container

import (
	. "syscall"
	"unsafe"

	"hakurei.app/ext"
)

// setNoNewPrivs sets the calling thread's no_new_privs attribute.
func setNoNewPrivs() error {
	return ext.Prctl(PR_SET_NO_NEW_PRIVS, 1, 0)
}

// schedParam is equivalent to struct sched_param from include/linux/sched.h.
type schedParam struct {
	// sched_priority
	priority ext.Int
}

// schedSetscheduler sets both the scheduling policy and parameters for the
// thread whose ID is specified in tid. If tid equals zero, the scheduling
// policy and parameters of the calling thread will be set.
//
// This function is unexported because it is [very subtle to use correctly]. The
// function signature in libc is misleading: pid actually refers to a thread ID.
// The glibc wrapper for this system call ignores this semantic and exposes
// this counterintuitive behaviour.
//
// This function is only called from the container setup thread. Do not reuse
// this if you do not have something similar in place!
//
// [very subtle to use correctly]: https://www.openwall.com/lists/musl/2016/03/01/4
func schedSetscheduler(tid int, policy ext.SchedPolicy, param *schedParam) error {
	if _, _, errno := Syscall(
		SYS_SCHED_SETSCHEDULER,
		uintptr(tid),
		uintptr(policy),
		uintptr(unsafe.Pointer(param)),
	); errno != 0 {
		return errno
	}
	return nil
}
