cargo/util/job.rs
1//! Job management (mostly for windows)
2//!
3//! Most of the time when you're running cargo you expect Ctrl-C to actually
4//! terminate the entire tree of processes in play, not just the one at the top
5//! (cargo). This currently works "by default" on Unix platforms because Ctrl-C
6//! actually sends a signal to the *process group* rather than the parent
7//! process, so everything will get torn down. On Windows, however, this does
8//! not happen and Ctrl-C just kills cargo.
9//!
10//! To achieve the same semantics on Windows we use Job Objects to ensure that
11//! all processes die at the same time. Job objects have a mode of operation
12//! where when all handles to the object are closed it causes all child
13//! processes associated with the object to be terminated immediately.
14//! Conveniently whenever a process in the job object spawns a new process the
15//! child will be associated with the job object as well. This means if we add
16//! ourselves to the job object we create then everything will get torn down!
17
18pub use self::imp::Setup;
19
20pub fn setup() -> Option<Setup> {
21 unsafe { imp::setup() }
22}
23
24#[cfg(unix)]
25mod imp {
26 use std::env;
27
28 pub type Setup = ();
29
30 pub unsafe fn setup() -> Option<()> {
31 // There's a test case for the behavior of
32 // when-cargo-is-killed-subprocesses-are-also-killed, but that requires
33 // one cargo spawned to become its own session leader, so we do that
34 // here.
35 //
36 // ALLOWED: For testing cargo itself only.
37 #[allow(clippy::disallowed_methods)]
38 if env::var("__CARGO_TEST_SETSID_PLEASE_DONT_USE_ELSEWHERE").is_ok() {
39 libc::setsid();
40 }
41 Some(())
42 }
43}
44
45#[cfg(windows)]
46mod imp {
47 use std::io;
48 use std::mem;
49 use std::ptr;
50 use std::ptr::addr_of;
51
52 use tracing::info;
53
54 use windows_sys::Win32::Foundation::CloseHandle;
55 use windows_sys::Win32::Foundation::HANDLE;
56 use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
57 use windows_sys::Win32::System::JobObjects::AssignProcessToJobObject;
58 use windows_sys::Win32::System::JobObjects::CreateJobObjectW;
59 use windows_sys::Win32::System::JobObjects::JobObjectExtendedLimitInformation;
60 use windows_sys::Win32::System::JobObjects::SetInformationJobObject;
61 use windows_sys::Win32::System::JobObjects::JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
62 use windows_sys::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
63 use windows_sys::Win32::System::Threading::GetCurrentProcess;
64
65 pub struct Setup {
66 job: Handle,
67 }
68
69 pub struct Handle {
70 inner: HANDLE,
71 }
72
73 fn last_err() -> io::Error {
74 io::Error::last_os_error()
75 }
76
77 pub unsafe fn setup() -> Option<Setup> {
78 // Creates a new job object for us to use and then adds ourselves to it.
79 // Note that all errors are basically ignored in this function,
80 // intentionally. Job objects are "relatively new" in Windows,
81 // particularly the ability to support nested job objects. Older
82 // Windows installs don't support this ability. We probably don't want
83 // to force Cargo to abort in this situation or force others to *not*
84 // use job objects, so we instead just ignore errors and assume that
85 // we're otherwise part of someone else's job object in this case.
86
87 let job = CreateJobObjectW(ptr::null_mut(), ptr::null());
88 if job == INVALID_HANDLE_VALUE {
89 return None;
90 }
91 let job = Handle { inner: job };
92
93 // Indicate that when all handles to the job object are gone that all
94 // process in the object should be killed. Note that this includes our
95 // entire process tree by default because we've added ourselves and
96 // our children will reside in the job once we spawn a process.
97 let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
98 info = mem::zeroed();
99 info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
100 let r = SetInformationJobObject(
101 job.inner,
102 JobObjectExtendedLimitInformation,
103 addr_of!(info) as *const _,
104 mem::size_of_val(&info) as u32,
105 );
106 if r == 0 {
107 return None;
108 }
109
110 // Assign our process to this job object, meaning that our children will
111 // now live or die based on our existence.
112 let me = GetCurrentProcess();
113 let r = AssignProcessToJobObject(job.inner, me);
114 if r == 0 {
115 return None;
116 }
117
118 Some(Setup { job })
119 }
120
121 impl Drop for Setup {
122 fn drop(&mut self) {
123 // On normal exits (not ctrl-c), we don't want to kill any child
124 // processes. The destructor here configures our job object to
125 // **not** kill everything on close, then closes the job object.
126 unsafe {
127 let info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
128 info = mem::zeroed();
129 let r = SetInformationJobObject(
130 self.job.inner,
131 JobObjectExtendedLimitInformation,
132 addr_of!(info) as *const _,
133 mem::size_of_val(&info) as u32,
134 );
135 if r == 0 {
136 info!("failed to configure job object to defaults: {}", last_err());
137 }
138 }
139 }
140 }
141
142 impl Drop for Handle {
143 fn drop(&mut self) {
144 unsafe {
145 CloseHandle(self.inner);
146 }
147 }
148 }
149}