Debian Codegraph @

.cargo/vendor/jobserver/src/windows.rs

raw
1 use crate::FromEnvErrorInner;
2 use std::ffi::CString;
3 use std::io;
4 use std::process::Command;
5 use std::ptr;
6 use std::sync::Arc;
7 use std::thread::{Builder, JoinHandle};
8
9 #[derive(Debug)]
10 pub struct Client {
11 sem: Handle,
12 name: String,
13 }
14
15 #[derive(Debug)]
16 pub struct Acquired;
17
18 #[allow(clippy::upper_case_acronyms)]
19 type BOOL = i32;
20 #[allow(clippy::upper_case_acronyms)]
21 type DWORD = u32;
22 #[allow(clippy::upper_case_acronyms)]
23 type HANDLE = *mut u8;
24 #[allow(clippy::upper_case_acronyms)]
25 type LONG = i32;
26
27 const ERROR_ALREADY_EXISTS: DWORD = 183;
28 const FALSE: BOOL = 0;
29 const INFINITE: DWORD = 0xffffffff;
30 const SEMAPHORE_MODIFY_STATE: DWORD = 0x2;
31 const SYNCHRONIZE: DWORD = 0x00100000;
32 const TRUE: BOOL = 1;
33
34 const WAIT_ABANDONED: DWORD = 128u32;
35 const WAIT_FAILED: DWORD = 4294967295u32;
36 const WAIT_OBJECT_0: DWORD = 0u32;
37 const WAIT_TIMEOUT: DWORD = 258u32;
38
39 extern "system" {
40 fn CloseHandle(handle: HANDLE) -> BOOL;
41 fn SetEvent(hEvent: HANDLE) -> BOOL;
42 fn WaitForMultipleObjects(
43 ncount: DWORD,
44 lpHandles: *const HANDLE,
45 bWaitAll: BOOL,
46 dwMilliseconds: DWORD,
47 ) -> DWORD;
48 fn CreateEventA(
49 lpEventAttributes: *mut u8,
50 bManualReset: BOOL,
51 bInitialState: BOOL,
52 lpName: *const i8,
53 ) -> HANDLE;
54 fn ReleaseSemaphore(
55 hSemaphore: HANDLE,
56 lReleaseCount: LONG,
57 lpPreviousCount: *mut LONG,
58 ) -> BOOL;
59 fn CreateSemaphoreA(
60 lpEventAttributes: *mut u8,
61 lInitialCount: LONG,
62 lMaximumCount: LONG,
63 lpName: *const i8,
64 ) -> HANDLE;
65 fn OpenSemaphoreA(dwDesiredAccess: DWORD, bInheritHandle: BOOL, lpName: *const i8) -> HANDLE;
66 fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
67 #[link_name = "SystemFunction036"]
68 fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: u32) -> u8;
69 }
70
71 // Note that we ideally would use the `getrandom` crate, but unfortunately
72 // that causes build issues when this crate is used in rust-lang/rust (see
73 // rust-lang/rust#65014 for more information). As a result we just inline
74 // the pretty simple Windows-specific implementation of generating
75 // randomness.
76 fn getrandom(dest: &mut [u8]) -> io::Result<()> {
77 // Prevent overflow of u32
78 for chunk in dest.chunks_mut(u32::MAX as usize) {
79 let ret = unsafe { RtlGenRandom(chunk.as_mut_ptr(), chunk.len() as u32) };
80 if ret == 0 {
81 return Err(io::Error::new(
82 io::ErrorKind::Other,
83 "failed to generate random bytes",
84 ));
85 }
86 }
87 Ok(())
88 }
89
90 impl Client {
91 pub fn new(limit: usize) -> io::Result<Client> {
92 // Try a bunch of random semaphore names until we get a unique one,
93 // but don't try for too long.
94 //
95 // Note that `limit == 0` is a valid argument above but Windows
96 // won't let us create a semaphore with 0 slots available to it. Get
97 // `limit == 0` working by creating a semaphore instead with one
98 // slot and then immediately acquire it (without ever releaseing it
99 // back).
100 for _ in 0..100 {
101 let mut bytes = [0; 4];
102 getrandom(&mut bytes)?;
103 let mut name = format!("__rust_jobserver_semaphore_{}\0", u32::from_ne_bytes(bytes));
104 unsafe {
105 let create_limit = if limit == 0 { 1 } else { limit };
106 let r = CreateSemaphoreA(
107 ptr::null_mut(),
108 create_limit as LONG,
109 create_limit as LONG,
110 name.as_ptr() as *const _,
111 );
112 if r.is_null() {
113 return Err(io::Error::last_os_error());
114 }
115 let handle = Handle(r);
116
117 let err = io::Error::last_os_error();
118 if err.raw_os_error() == Some(ERROR_ALREADY_EXISTS as i32) {
119 continue;
120 }
121 name.pop(); // chop off the trailing nul
122 let client = Client { sem: handle, name };
123 if create_limit != limit {
124 client.acquire()?;
125 }
126 return Ok(client);
127 }
128 }
129
130 Err(io::Error::new(
131 io::ErrorKind::Other,
132 "failed to find a unique name for a semaphore",
133 ))
134 }
135
136 pub(crate) unsafe fn open(s: &str, _check_pipe: bool) -> Result<Client, FromEnvErrorInner> {
137 let name = match CString::new(s) {
138 Ok(s) => s,
139 Err(e) => return Err(FromEnvErrorInner::CannotParse(e.to_string())),
140 };
141
142 let sem = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, FALSE, name.as_ptr());
143 if sem.is_null() {
144 Err(FromEnvErrorInner::CannotOpenPath(
145 s.to_string(),
146 io::Error::last_os_error(),
147 ))
148 } else {
149 Ok(Client {
150 sem: Handle(sem),
151 name: s.to_string(),
152 })
153 }
154 }
155
156 pub fn acquire(&self) -> io::Result<Acquired> {
157 unsafe {
158 let r = WaitForSingleObject(self.sem.0, INFINITE);
159 if r == WAIT_OBJECT_0 {
160 Ok(Acquired)
161 } else {
162 Err(io::Error::last_os_error())
163 }
164 }
165 }
166
167 pub fn try_acquire(&self) -> io::Result<Option<Acquired>> {
168 match unsafe { WaitForSingleObject(self.sem.0, 0) } {
169 WAIT_OBJECT_0 => Ok(Some(Acquired)),
170 WAIT_TIMEOUT => Ok(None),
171 WAIT_FAILED => Err(io::Error::last_os_error()),
172 // We believe this should be impossible for a semaphore, but still
173 // check the error code just in case it happens.
174 WAIT_ABANDONED => Err(io::Error::new(
175 io::ErrorKind::Other,
176 "Wait on jobserver semaphore returned WAIT_ABANDONED",
177 )),
178 _ => unreachable!("Unexpected return value from WaitForSingleObject"),
179 }
180 }
181
182 pub fn release(&self, _data: Option<&Acquired>) -> io::Result<()> {
183 unsafe {
184 let r = ReleaseSemaphore(self.sem.0, 1, ptr::null_mut());
185 if r != 0 {
186 Ok(())
187 } else {
188 Err(io::Error::last_os_error())
189 }
190 }
191 }
192
193 pub fn string_arg(&self) -> String {
194 self.name.clone()
195 }
196
197 pub fn available(&self) -> io::Result<usize> {
198 // Can't read value of a semaphore on Windows, so
199 // try to acquire without sleeping, since we can find out the
200 // old value on release. If acquisiton fails, then available is 0.
201 unsafe {
202 let r = WaitForSingleObject(self.sem.0, 0);
203 if r != WAIT_OBJECT_0 {
204 Ok(0)
205 } else {
206 let mut prev: LONG = 0;
207 let r = ReleaseSemaphore(self.sem.0, 1, &mut prev);
208 if r != 0 {
209 Ok(prev as usize + 1)
210 } else {
211 Err(io::Error::last_os_error())
212 }
213 }
214 }
215 }
216
217 pub fn configure(&self, _cmd: &mut Command) {
218 // nothing to do here, we gave the name of our semaphore to the
219 // child above
220 }
221 }
222
223 #[derive(Debug)]
224 struct Handle(HANDLE);
225 // HANDLE is a raw ptr, but we're send/sync
226 unsafe impl Sync for Handle {}
227 unsafe impl Send for Handle {}
228
229 impl Drop for Handle {
230 fn drop(&mut self) {
231 unsafe {
232 CloseHandle(self.0);
233 }
234 }
235 }
236
237 #[derive(Debug)]
238 pub struct Helper {
239 event: Arc<Handle>,
240 thread: JoinHandle<()>,
241 }
242
243 pub(crate) fn spawn_helper(
244 client: crate::Client,
245 state: Arc<super::HelperState>,
246 mut f: Box<dyn FnMut(io::Result<crate::Acquired>) + Send>,
247 ) -> io::Result<Helper> {
248 let event = unsafe {
249 let r = CreateEventA(ptr::null_mut(), TRUE, FALSE, ptr::null());
250 if r.is_null() {
251 return Err(io::Error::last_os_error());
252 } else {
253 Handle(r)
254 }
255 };
256 let event = Arc::new(event);
257 let event2 = event.clone();
258 let thread = Builder::new().spawn(move || {
259 let objects = [event2.0, client.inner.sem.0];
260 state.for_each_request(|_| {
261 const WAIT_OBJECT_1: u32 = WAIT_OBJECT_0 + 1;
262 match unsafe { WaitForMultipleObjects(2, objects.as_ptr(), FALSE, INFINITE) } {
263 WAIT_OBJECT_0 => {}
264 WAIT_OBJECT_1 => f(Ok(crate::Acquired {
265 client: client.inner.clone(),
266 data: Acquired,
267 disabled: false,
268 })),
269 _ => f(Err(io::Error::last_os_error())),
270 }
271 });
272 })?;
273 Ok(Helper { thread, event })
274 }
275
276 impl Helper {
277 pub fn join(self) {
278 // Unlike unix this logic is much easier. If our thread was blocked
279 // in waiting for requests it should already be woken up and
280 // exiting. Otherwise it's waiting for a token, so we wake it up
281 // with a different event that it's also waiting on here. After
282 // these two we should be guaranteed the thread is on its way out,
283 // so we can safely `join`.
284 let r = unsafe { SetEvent(self.event.0) };
285 if r == 0 {
286 panic!("failed to set event: {}", io::Error::last_os_error());
287 }
288 drop(self.thread.join());
289 }
290 }