Skip to main content

bootstrap/utils/
job.rs

1#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))]
2pub(crate) use self::for_unix::setup;
3#[cfg(windows)]
4pub(crate) use self::for_windows::setup;
5use crate::core::session::Session;
6
7#[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))]
8pub(crate) fn setup(_sess: &Session) {}
9
10#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))]
11mod for_unix {
12    use std::ffi::c_int;
13    use std::io;
14
15    use libc::id_t;
16
17    fn get_priority(which: c_int, who: id_t) -> io::Result<c_int> {
18        // Genius design: `getpriority` can return -1 on success if the nice value is literally -1.
19        // Per `getpriority`'s docs, clear `errno` beforehand and check it afterward regardless of
20        // return value.
21        errno::set_errno(errno::Errno(0));
22        // SAFETY: empty safety contract
23        let nice = unsafe { libc::getpriority(which as _, who) };
24        let new_errno = errno::errno().0;
25        if new_errno == 0 { Ok(nice) } else { Err(io::Error::from_raw_os_error(new_errno)) }
26    }
27    fn set_priority(which: c_int, who: id_t, prio: c_int) -> io::Result<()> {
28        // SAFETY: empty safety contract
29        if unsafe { libc::setpriority(which as _, who, prio) != -1 } {
30            Ok(())
31        } else {
32            Err(io::Error::last_os_error())
33        }
34    }
35
36    pub(crate) fn setup(sess: &super::Session) {
37        const TARGET_NICE: c_int = 10;
38        // The processes that spawn the build are all descendants of the
39        // current thread.
40        let (which, who) = (libc::PRIO_PROCESS as _, 0);
41        // Unwrap both of those to alert users to ridiculous Seccomp-BPF setups messing up their
42        // performance.
43        if sess.config.low_priority && get_priority(which, who).unwrap() < TARGET_NICE {
44            set_priority(which, who, TARGET_NICE).unwrap();
45        }
46    }
47}
48
49/// Job management on Windows for bootstrapping
50///
51/// Most of the time when you're running a build system (e.g., make) you expect
52/// Ctrl-C or abnormal termination to actually terminate the entire tree of
53/// processes in play. This currently works "by
54/// default" on Unix platforms because Ctrl-C actually sends a signal to the
55/// *process group* so everything will get torn
56/// down. On Windows, however, Ctrl-C is only sent to processes in the same console.
57/// If a process is detached or attached to another console, it won't receive the
58/// signal.
59///
60/// To achieve the same semantics on Windows we use Job Objects to ensure that
61/// all processes die at the same time. Job objects have a mode of operation
62/// where when all handles to the object are closed it causes all child
63/// processes associated with the object to be terminated immediately.
64/// Conveniently whenever a process in the job object spawns a new process the
65/// child will be associated with the job object as well. This means if we add
66/// ourselves to the job object we create then everything will get torn down!
67///
68/// Unfortunately most of the time the build system is actually called from a
69/// python wrapper (which manages things like building the build system) so this
70/// all doesn't quite cut it so far. To go the last mile we duplicate the job
71/// object handle into our parent process (a python process probably) and then
72/// close our own handle. This means that the only handle to the job object
73/// resides in the parent python process, so when python dies the whole build
74/// system dies (as one would probably expect!).
75///
76/// Note that this is a Windows specific module as none of this logic is required on Unix.
77#[cfg(windows)]
78mod for_windows {
79    use std::ffi::c_void;
80    use std::io;
81
82    use windows::Win32::Foundation::CloseHandle;
83    use windows::Win32::System::Diagnostics::Debug::{
84        SEM_NOGPFAULTERRORBOX, SetErrorMode, THREAD_ERROR_MODE,
85    };
86    use windows::Win32::System::JobObjects::{
87        AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
88        JOB_OBJECT_LIMIT_PRIORITY_CLASS, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
89        JobObjectExtendedLimitInformation, SetInformationJobObject,
90    };
91    use windows::Win32::System::Threading::{BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess};
92    use windows::core::PCWSTR;
93
94    pub(crate) fn setup(sess: &super::Session) {
95        // SAFETY: pretty much everything below is unsafe
96        unsafe {
97            // Enable the Windows Error Reporting dialog which msys disables,
98            // so we can JIT debug rustc
99            let mode = SetErrorMode(THREAD_ERROR_MODE::default());
100            SetErrorMode(mode & !SEM_NOGPFAULTERRORBOX);
101
102            // Create a new job object for us to use
103            let job = CreateJobObjectW(None, PCWSTR::null()).unwrap();
104
105            // Indicate that when all handles to the job object are gone that all
106            // process in the object should be killed. Note that this includes our
107            // entire process tree by default because we've added ourselves and our
108            // children will reside in the job by default.
109            let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
110            info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
111            if sess.config.low_priority {
112                info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PRIORITY_CLASS;
113                info.BasicLimitInformation.PriorityClass = BELOW_NORMAL_PRIORITY_CLASS.0;
114            }
115            let r = SetInformationJobObject(
116                job,
117                JobObjectExtendedLimitInformation,
118                &info as *const _ as *const c_void,
119                size_of_val(&info) as u32,
120            );
121            assert!(r.is_ok(), "{}", io::Error::last_os_error());
122
123            // Assign our process to this job object.
124            let r = AssignProcessToJobObject(job, GetCurrentProcess());
125            if r.is_err() {
126                CloseHandle(job).ok();
127                return;
128            }
129        }
130
131        // Note: we intentionally leak the job object handle. When our process exits
132        // (normally or abnormally) it will close the handle implicitly, causing all
133        // processes in the job to be cleaned up.
134    }
135}