1use std::io;
5
6use crate::Termination;
7
8pub fn exit_without_handlers(code: u8) -> ! {
14 #[cfg(unix)]
15 {
16 unsafe { libc::_exit(libc::c_int::from(code)) }
18 }
19 #[cfg(windows)]
20 {
21 use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
22 if unsafe { TerminateProcess(GetCurrentProcess(), u32::from(code)) } != 0 {
24 loop {
25 std::thread::park();
26 }
27 }
28 std::process::exit(i32::from(code))
29 }
30 #[cfg(not(any(unix, windows)))]
31 std::process::exit(i32::from(code))
32}
33
34pub fn stop_std_handle_inheritance() {
40 #[cfg(windows)]
41 {
42 use windows_sys::Win32::Foundation::{
43 HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, SetHandleInformation,
44 };
45 use windows_sys::Win32::System::Console::{
46 GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
47 };
48 for stream in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
49 let handle = unsafe { GetStdHandle(stream) };
51 if handle.is_null() || handle == INVALID_HANDLE_VALUE {
52 continue;
53 }
54 let _ = unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) };
56 }
57 }
58}
59
60pub fn claim_stdout() -> io::Result<std::fs::File> {
70 #[cfg(unix)]
71 {
72 crate::platform::claim_stream(libc::STDOUT_FILENO, libc::STDERR_FILENO)
73 }
74 #[cfg(windows)]
75 {
76 crate::platform::claim_stdout()
77 }
78 #[cfg(not(any(unix, windows)))]
79 {
80 Err(io::Error::from(io::ErrorKind::Unsupported))
81 }
82}
83
84pub(crate) const PARENT_EXITED_NAME: &str = "PARENT_EXITED";
85
86const PARENT_EXITED: Termination = Termination::new(PARENT_EXITED_NAME, 143, false);
88
89pub fn watch_parent() -> io::Result<()> {
103 let handler = crate::platform::termination_handler().ok_or_else(|| {
104 io::Error::new(
105 io::ErrorKind::NotFound,
106 "no termination handler is installed",
107 )
108 })?;
109 let Some(parent) = platform::Parent::open()? else {
110 return Ok(());
111 };
112 std::thread::Builder::new()
113 .name("alpha2-parent-watch".to_owned())
114 .spawn(move || {
115 if parent.wait() {
116 handler(PARENT_EXITED);
117 }
118 })?;
119 Ok(())
120}
121
122pub struct KillOnCloseJob {
125 #[cfg(windows)]
126 handle: platform::OwnedHandle,
127}
128
129impl KillOnCloseJob {
130 pub fn new() -> io::Result<Self> {
135 Ok(Self {
136 #[cfg(windows)]
137 handle: platform::kill_on_close_job()?,
138 })
139 }
140
141 pub fn assign(&self, child: &std::process::Child) -> io::Result<()> {
146 #[cfg(windows)]
147 {
148 platform::assign(&self.handle, child)
149 }
150 #[cfg(not(windows))]
151 {
152 let _ = child;
153 Ok(())
154 }
155 }
156}
157
158impl std::fmt::Debug for KillOnCloseJob {
159 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160 formatter
161 .debug_struct("KillOnCloseJob")
162 .finish_non_exhaustive()
163 }
164}
165
166#[cfg(target_os = "linux")]
167mod platform {
168 use std::io;
169
170 pub(super) struct Parent(Option<std::fs::File>);
172
173 impl Parent {
174 pub(super) fn open() -> io::Result<Option<Self>> {
175 use std::os::fd::FromRawFd;
176 let parent = unsafe { libc::getppid() };
178 if parent <= 1 {
179 return Ok(None);
180 }
181 let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, parent, 0) };
183 if fd < 0 {
184 let error = io::Error::last_os_error();
185 return match error.raw_os_error() {
186 Some(libc::ESRCH) => Ok(Some(Self(None))),
187 Some(libc::ENOSYS) => death_signal(parent),
188 _ => Err(error),
189 };
190 }
191 let fd = libc::c_int::try_from(fd)
192 .map_err(|_| io::Error::other("pidfd_open returned an impossible descriptor"))?;
193 let pidfd = unsafe { std::fs::File::from_raw_fd(fd) };
195 if unsafe { libc::getppid() } != parent {
198 return Ok(Some(Self(None)));
199 }
200 Ok(Some(Self(Some(pidfd))))
201 }
202
203 pub(super) fn wait(&self) -> bool {
205 use std::os::fd::AsRawFd;
206 let Some(pidfd) = &self.0 else {
207 return true;
208 };
209 let mut poll = libc::pollfd {
210 fd: pidfd.as_raw_fd(),
211 events: libc::POLLIN,
212 revents: 0,
213 };
214 loop {
215 let ready = unsafe { libc::poll(&raw mut poll, 1, -1) };
217 if ready > 0 {
218 return true;
219 }
220 if ready < 0 && io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
221 return false;
222 }
223 }
224 }
225 }
226
227 fn death_signal(parent: libc::pid_t) -> io::Result<Option<Parent>> {
229 if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) } != 0 {
231 return Err(io::Error::last_os_error());
232 }
233 if unsafe { libc::getppid() } != parent {
236 return Ok(Some(Parent(None)));
237 }
238 Ok(None)
239 }
240}
241
242#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
243mod platform {
244 use std::io;
245
246 pub(super) struct Parent(Option<std::fs::File>);
248
249 impl Parent {
250 pub(super) fn open() -> io::Result<Option<Self>> {
251 use std::os::fd::{AsRawFd, FromRawFd};
252 let parent = unsafe { libc::getppid() };
254 if parent <= 1 {
255 return Ok(None);
256 }
257 let fd = unsafe { libc::kqueue() };
259 if fd < 0 {
260 return Err(io::Error::last_os_error());
261 }
262 let queue = unsafe { std::fs::File::from_raw_fd(fd) };
264 let mut change: libc::kevent = unsafe { std::mem::zeroed() };
266 change.ident = usize::try_from(parent).unwrap_or(0);
267 change.filter = libc::EVFILT_PROC;
268 change.flags = libc::EV_ADD | libc::EV_ONESHOT;
269 change.fflags = libc::NOTE_EXIT;
270 let registered = unsafe {
272 libc::kevent(
273 queue.as_raw_fd(),
274 &raw const change,
275 1,
276 std::ptr::null_mut(),
277 0,
278 std::ptr::null(),
279 )
280 };
281 if registered < 0 {
282 let error = io::Error::last_os_error();
283 return if error.raw_os_error() == Some(libc::ESRCH) {
284 Ok(Some(Self(None)))
285 } else {
286 Err(error)
287 };
288 }
289 if unsafe { libc::getppid() } != parent {
292 return Ok(Some(Self(None)));
293 }
294 Ok(Some(Self(Some(queue))))
295 }
296
297 pub(super) fn wait(&self) -> bool {
299 use std::os::fd::AsRawFd;
300 let Some(queue) = &self.0 else {
301 return true;
302 };
303 loop {
304 let mut event: libc::kevent = unsafe { std::mem::zeroed() };
306 let ready = unsafe {
308 libc::kevent(
309 queue.as_raw_fd(),
310 std::ptr::null(),
311 0,
312 &raw mut event,
313 1,
314 std::ptr::null(),
315 )
316 };
317 if ready > 0 {
318 return true;
319 }
320 if ready < 0 && io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
321 return false;
322 }
323 }
324 }
325 }
326}
327
328#[cfg(windows)]
329mod platform {
330 use std::io;
331 use std::os::windows::io::AsRawHandle;
332
333 use windows_sys::Win32::Foundation::{
334 CloseHandle, ERROR_INVALID_PARAMETER, FILETIME, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
335 };
336 use windows_sys::Win32::System::Diagnostics::ToolHelp::{
337 CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
338 TH32CS_SNAPPROCESS,
339 };
340 use windows_sys::Win32::System::JobObjects::{
341 AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
342 JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
343 SetInformationJobObject,
344 };
345 use windows_sys::Win32::System::Threading::{
346 GetCurrentProcess, GetCurrentProcessId, GetProcessTimes, INFINITE, OpenProcess,
347 PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, WaitForSingleObject,
348 };
349
350 pub(super) struct OwnedHandle(HANDLE);
351
352 unsafe impl Send for OwnedHandle {}
354 unsafe impl Sync for OwnedHandle {}
356
357 impl Drop for OwnedHandle {
358 fn drop(&mut self) {
359 unsafe { CloseHandle(self.0) };
361 }
362 }
363
364 pub(super) struct Parent(Option<OwnedHandle>);
366
367 impl Parent {
368 pub(super) fn open() -> io::Result<Option<Self>> {
369 let Some(parent) = parent_id()? else {
370 return Ok(None);
371 };
372 let handle = unsafe {
374 OpenProcess(
375 PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
376 0,
377 parent,
378 )
379 };
380 if handle.is_null() {
381 let error = io::Error::last_os_error();
382 return if error.raw_os_error() == i32::try_from(ERROR_INVALID_PARAMETER).ok() {
383 Ok(Some(Self(None)))
384 } else {
385 Err(error)
386 };
387 }
388 let handle = OwnedHandle(handle);
389 let ours = created(unsafe { GetCurrentProcess() })?;
391 if created(handle.0)? > ours {
393 return Ok(Some(Self(None)));
394 }
395 Ok(Some(Self(Some(handle))))
396 }
397
398 pub(super) fn wait(&self) -> bool {
400 let Some(handle) = &self.0 else {
401 return true;
402 };
403 unsafe { WaitForSingleObject(handle.0, INFINITE) == WAIT_OBJECT_0 }
405 }
406 }
407
408 fn parent_id() -> io::Result<Option<u32>> {
409 let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
411 if snapshot == INVALID_HANDLE_VALUE {
412 return Err(io::Error::last_os_error());
413 }
414 let snapshot = OwnedHandle(snapshot);
415 let ours = unsafe { GetCurrentProcessId() };
417 let mut entry = PROCESSENTRY32W {
418 dwSize: u32::try_from(std::mem::size_of::<PROCESSENTRY32W>()).unwrap_or(0),
419 ..PROCESSENTRY32W::default()
420 };
421 let mut more = unsafe { Process32FirstW(snapshot.0, &raw mut entry) } != 0;
423 while more {
424 if entry.th32ProcessID == ours {
425 return Ok(Some(entry.th32ParentProcessID).filter(|parent| *parent != 0));
426 }
427 more = unsafe { Process32NextW(snapshot.0, &raw mut entry) } != 0;
429 }
430 Ok(None)
431 }
432
433 fn created(process: HANDLE) -> io::Result<u64> {
435 let zero = || FILETIME {
436 dwLowDateTime: 0,
437 dwHighDateTime: 0,
438 };
439 let (mut created, mut exited, mut kernel, mut user) = (zero(), zero(), zero(), zero());
440 let read = unsafe {
442 GetProcessTimes(
443 process,
444 &raw mut created,
445 &raw mut exited,
446 &raw mut kernel,
447 &raw mut user,
448 )
449 };
450 if read == 0 {
451 return Err(io::Error::last_os_error());
452 }
453 Ok(u64::from(created.dwHighDateTime) << 32 | u64::from(created.dwLowDateTime))
454 }
455
456 pub(super) fn kill_on_close_job() -> io::Result<OwnedHandle> {
457 let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
459 if job.is_null() {
460 return Err(io::Error::last_os_error());
461 }
462 let job = OwnedHandle(job);
463 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
464 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
465 let set = unsafe {
467 SetInformationJobObject(
468 job.0,
469 JobObjectExtendedLimitInformation,
470 (&raw const limits).cast(),
471 u32::try_from(std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
472 .unwrap_or(0),
473 )
474 };
475 if set == 0 {
476 return Err(io::Error::last_os_error());
477 }
478 Ok(job)
479 }
480
481 pub(super) fn assign(job: &OwnedHandle, child: &std::process::Child) -> io::Result<()> {
482 if unsafe { AssignProcessToJobObject(job.0, child.as_raw_handle()) } == 0 {
484 return Err(io::Error::last_os_error());
485 }
486 Ok(())
487 }
488}
489
490#[cfg(not(any(
491 target_os = "linux",
492 target_os = "macos",
493 target_os = "ios",
494 target_os = "freebsd",
495 windows
496)))]
497mod platform {
498 use std::io;
499
500 pub(super) struct Parent;
502
503 #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
505 impl Parent {
506 pub(super) fn open() -> io::Result<Option<Self>> {
507 Ok(None)
508 }
509
510 pub(super) fn wait(&self) -> bool {
511 false
512 }
513 }
514}
515
516#[cfg(test)]
517#[path = "lifetime_tests.rs"]
518mod tests;