use std::ffi::c_void;
use windows::core::PCWSTR;
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectCpuRateControlInformation,
JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject,
JOBOBJECT_CPU_RATE_CONTROL_INFORMATION, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_CPU_RATE_CONTROL_ENABLE, JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP,
JOB_OBJECT_LIMIT_JOB_MEMORY, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
use cellos_core::CellosError;
pub(crate) struct JobObject {
handle: HANDLE,
}
unsafe impl Send for JobObject {}
unsafe impl Sync for JobObject {}
impl JobObject {
pub(crate) fn create(
memory_max_bytes: Option<u64>,
cpu_rate_hundredths_percent: Option<u32>,
) -> Result<Self, CellosError> {
let handle = unsafe { CreateJobObjectW(None, PCWSTR::null()) }
.map_err(|e| CellosError::Host(format!("CreateJobObjectW failed: {e}")))?;
let job = Self { handle };
let mut ext = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
ext.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if let Some(bytes) = memory_max_bytes {
ext.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
ext.JobMemoryLimit = bytes as usize;
}
unsafe {
SetInformationJobObject(
job.handle,
JobObjectExtendedLimitInformation,
&ext as *const _ as *const c_void,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
}
.map_err(|e| {
CellosError::Host(format!(
"SetInformationJobObject(extended limits) failed: {e}"
))
})?;
if let Some(rate) = cpu_rate_hundredths_percent {
let mut cpu: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION = unsafe { std::mem::zeroed() };
cpu.ControlFlags =
JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP;
cpu.Anonymous.CpuRate = rate.clamp(1, 10_000);
unsafe {
SetInformationJobObject(
job.handle,
JobObjectCpuRateControlInformation,
&cpu as *const _ as *const c_void,
std::mem::size_of::<JOBOBJECT_CPU_RATE_CONTROL_INFORMATION>() as u32,
)
}
.map_err(|e| {
CellosError::Host(format!("SetInformationJobObject(cpu rate) failed: {e}"))
})?;
}
Ok(job)
}
pub(crate) fn assign(&self, process: HANDLE) -> Result<(), CellosError> {
unsafe { AssignProcessToJobObject(self.handle, process) }
.map_err(|e| CellosError::Host(format!("AssignProcessToJobObject failed: {e}")))
}
pub(crate) fn terminate(&self, exit_code: u32) -> Result<(), CellosError> {
unsafe { TerminateJobObject(self.handle, exit_code) }
.map_err(|e| CellosError::Host(format!("TerminateJobObject failed: {e}")))
}
}
impl Drop for JobObject {
fn drop(&mut self) {
unsafe {
let _ = CloseHandle(self.handle);
}
}
}