1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Job objects that bind a child's lifetime and resources to the parent.
#![allow(unsafe_code)]
use std::io;
use std::mem::size_of;
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, OwnedHandle, RawHandle};
use std::ptr::{null, null_mut};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
QueryInformationJobObject, SetInformationJobObject, TerminateJobObject,
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_ACTIVE_PROCESS,
JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION, JOB_OBJECT_LIMIT_JOB_MEMORY,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_LIMIT_PROCESS_MEMORY,
};
use crate::handle::{current_process, owned_from_creation};
use crate::security::SecurityDescriptor;
/// The limits a [`Job`] enforces.
///
/// Built with the setter methods, which can be chained:
///
/// ```
/// # #[cfg(windows)] {
/// use win_custody::JobLimits;
///
/// let limits = JobLimits::new()
/// .kill_on_close(true)
/// .active_processes(1)
/// .process_memory(256 * 1024 * 1024);
/// assert!(limits.kills_on_close());
/// assert_eq!(limits.active_process_limit(), Some(1));
/// # }
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct JobLimits {
kill_on_close: bool,
die_on_unhandled_exception: bool,
active_processes: Option<u32>,
process_memory: Option<usize>,
job_memory: Option<usize>,
}
impl JobLimits {
/// No limits at all.
pub const fn new() -> Self {
Self {
kill_on_close: false,
die_on_unhandled_exception: false,
active_processes: None,
process_memory: None,
job_memory: None,
}
}
/// Kill every process in the job when the last handle to the job closes,
/// including when the owning process is killed.
#[must_use]
pub const fn kill_on_close(mut self, enabled: bool) -> Self {
self.kill_on_close = enabled;
self
}
/// Makes every process in the job behave as if it called
/// `SetErrorMode(SEM_NOGPFAULTERRORBOX)`. A debugger still gets a chance to
/// handle an unhandled exception. Without one, the process ends with the
/// exception code as its exit code instead of waiting behind the Windows
/// Error Reporting fault dialog.
#[must_use]
pub const fn die_on_unhandled_exception(mut self, enabled: bool) -> Self {
self.die_on_unhandled_exception = enabled;
self
}
/// At most `limit` processes may be active in the job at once. Assigning
/// or creating one more fails.
#[must_use]
pub const fn active_processes(mut self, limit: u32) -> Self {
self.active_processes = Some(limit);
self
}
/// Each process may commit at most `bytes` of memory.
#[must_use]
pub const fn process_memory(mut self, bytes: usize) -> Self {
self.process_memory = Some(bytes);
self
}
/// All processes in the job together may commit at most `bytes`.
#[must_use]
pub const fn job_memory(mut self, bytes: usize) -> Self {
self.job_memory = Some(bytes);
self
}
/// Whether the job kills its processes when its last handle closes.
pub const fn kills_on_close(&self) -> bool {
self.kill_on_close
}
/// Whether processes in the job end on an unhandled exception instead of
/// waiting behind the fault dialog.
pub const fn dies_on_unhandled_exception(&self) -> bool {
self.die_on_unhandled_exception
}
/// The active-process limit, if one is set.
pub const fn active_process_limit(&self) -> Option<u32> {
self.active_processes
}
/// The per-process commit limit in bytes, if one is set.
pub const fn process_memory_limit(&self) -> Option<usize> {
self.process_memory
}
/// The whole-job commit limit in bytes, if one is set.
pub const fn job_memory_limit(&self) -> Option<usize> {
self.job_memory
}
fn validate(&self) -> io::Result<()> {
if self.active_processes == Some(0)
|| self.process_memory == Some(0)
|| self.job_memory == Some(0)
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"a zero job limit would refuse every process",
));
}
Ok(())
}
fn to_raw(self) -> JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
let mut raw = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
let basic = &mut raw.BasicLimitInformation;
if self.kill_on_close {
basic.LimitFlags |= JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
}
if self.die_on_unhandled_exception {
basic.LimitFlags |= JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
}
if let Some(limit) = self.active_processes {
basic.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
basic.ActiveProcessLimit = limit;
}
if let Some(bytes) = self.process_memory {
basic.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY;
raw.ProcessMemoryLimit = bytes;
}
if let Some(bytes) = self.job_memory {
raw.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
raw.JobMemoryLimit = bytes;
}
raw
}
fn from_raw(raw: &JOBOBJECT_EXTENDED_LIMIT_INFORMATION) -> Self {
let flags = raw.BasicLimitInformation.LimitFlags;
Self {
kill_on_close: flags & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE != 0,
die_on_unhandled_exception: flags & JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION != 0,
active_processes: (flags & JOB_OBJECT_LIMIT_ACTIVE_PROCESS != 0)
.then_some(raw.BasicLimitInformation.ActiveProcessLimit),
process_memory: (flags & JOB_OBJECT_LIMIT_PROCESS_MEMORY != 0)
.then_some(raw.ProcessMemoryLimit),
job_memory: (flags & JOB_OBJECT_LIMIT_JOB_MEMORY != 0).then_some(raw.JobMemoryLimit),
}
}
}
/// An anonymous job object whose limits are in force before the first
/// process can join it.
#[derive(Debug)]
pub struct Job(OwnedHandle);
impl Job {
/// Creates a job with `limits` and the creator's default security.
pub fn create(limits: &JobLimits) -> io::Result<Self> {
Self::create_inner(limits, None)
}
/// Creates a job with `limits`, protected by `descriptor`.
pub fn create_with_security(
limits: &JobLimits,
descriptor: &SecurityDescriptor,
) -> io::Result<Self> {
Self::create_inner(limits, Some(descriptor))
}
fn create_inner(
limits: &JobLimits,
descriptor: Option<&SecurityDescriptor>,
) -> io::Result<Self> {
limits.validate()?;
let attributes = descriptor.map(|descriptor| descriptor.attributes(false));
let attributes_pointer = attributes
.as_ref()
.map_or(null(), |attributes| attributes.as_ptr());
// SAFETY: the attribute block, when present, and the descriptor it
// points at outlive the call; no name is passed.
let handle = unsafe { CreateJobObjectW(attributes_pointer, null()) };
let job = Self(owned_from_creation(handle)?);
let raw = limits.to_raw();
// SAFETY: the job handle is live; the buffer pointer and length
// describe exactly the local limit structure.
let set = unsafe {
SetInformationJobObject(
job.raw(),
JobObjectExtendedLimitInformation,
(&raw as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
};
if set == 0 {
return Err(io::Error::last_os_error());
}
Ok(job)
}
/// Assigns `process` to the job. The handle needs `PROCESS_SET_QUOTA`
/// and `PROCESS_TERMINATE`, which a process this one created has.
///
/// Until this returns, the process is outside the job. For a child you
/// are about to create, use [`Launch::spawn_in_job`](crate::Launch::spawn_in_job)
/// or [`Launch::spawn_suspended_in_job`](crate::Launch::spawn_suspended_in_job),
/// which create it inside the job; a child created first and assigned
/// afterwards outlives a kill-on-close job if this process is killed
/// between the two steps.
pub fn assign(&self, process: &impl AsHandle) -> io::Result<()> {
let process = process.as_handle().as_raw_handle();
// SAFETY: both handles are live for the call.
if unsafe { AssignProcessToJobObject(self.raw(), process) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
/// Puts the calling process in the job and keeps the job handle open for
/// the rest of its life. With [`JobLimits::kill_on_close`], every
/// descendant then dies with this process, however it ends.
pub fn assign_current_process(self) -> io::Result<()> {
// SAFETY: the job handle is live; GetCurrentProcess returns a valid
// pseudo-handle that does not need to be closed.
if unsafe { AssignProcessToJobObject(self.raw(), current_process()) } == 0 {
return Err(io::Error::last_os_error());
}
// The handle must outlive every process in the job, and this process
// is one of them, so it is deliberately never closed.
std::mem::forget(self);
Ok(())
}
/// Terminates every process in the job with `exit_code`.
pub fn terminate(&self, exit_code: u32) -> io::Result<()> {
// SAFETY: the handle is live; the call takes no pointers.
if unsafe { TerminateJobObject(self.raw(), exit_code) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
/// Reads the limits back from the kernel.
pub fn limits(&self) -> io::Result<JobLimits> {
let mut raw = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
// SAFETY: the handle is live; the buffer pointer and length describe
// exactly the local limit structure and the returned-length pointer is
// null, which the API permits.
let queried = unsafe {
QueryInformationJobObject(
self.raw(),
JobObjectExtendedLimitInformation,
(&mut raw as *mut JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
null_mut(),
)
};
if queried == 0 {
return Err(io::Error::last_os_error());
}
Ok(JobLimits::from_raw(&raw))
}
fn raw(&self) -> RawHandle {
self.0.as_raw_handle()
}
}
impl AsHandle for Job {
fn as_handle(&self) -> BorrowedHandle<'_> {
self.0.as_handle()
}
}
impl AsRawHandle for Job {
fn as_raw_handle(&self) -> RawHandle {
self.raw()
}
}
impl From<Job> for OwnedHandle {
fn from(job: Job) -> Self {
job.0
}
}
#[cfg(test)]
mod tests {
use super::{Job, JobLimits};
#[test]
fn limits_read_back_as_they_were_set() {
let limits = JobLimits::new()
.kill_on_close(true)
.die_on_unhandled_exception(true)
.active_processes(1)
.process_memory(256 * 1024 * 1024)
.job_memory(512 * 1024 * 1024);
let job = Job::create(&limits).unwrap();
assert_eq!(job.limits().unwrap(), limits);
}
#[test]
fn an_empty_limit_set_reads_back_empty() {
let job = Job::create(&JobLimits::new()).unwrap();
assert_eq!(job.limits().unwrap(), JobLimits::new());
}
#[test]
fn zero_limits_are_refused_before_the_job_exists() {
for limits in [
JobLimits::new().active_processes(0),
JobLimits::new().process_memory(0),
JobLimits::new().job_memory(0),
] {
let error = Job::create(&limits).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
}
}
}