1use std::fmt;
32use std::sync::atomic::{AtomicBool, Ordering};
33
34use sysprims_core::{SysprimsError, SysprimsResult};
35
36use crate::{resolve_signal_name, validate_pid, FORCE_KILL_SIGNAL, TERMINATE_SIGNAL};
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum SignalBinding {
42 Bound,
46 CheckedNumeric,
50}
51
52impl SignalBinding {
53 pub const fn as_str(self) -> &'static str {
55 match self {
56 Self::Bound => "bound",
57 Self::CheckedNumeric => "checked_numeric",
58 }
59 }
60}
61
62impl fmt::Display for SignalBinding {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.write_str(self.as_str())
65 }
66}
67
68#[cfg(target_os = "linux")]
69static FORCE_LINUX_CHECKED_NUMERIC: AtomicBool = AtomicBool::new(false);
70
71#[doc(hidden)]
74pub fn with_forced_checked_numeric_for_test<F, R>(f: F) -> R
75where
76 F: FnOnce() -> R,
77{
78 #[cfg(target_os = "linux")]
79 {
80 struct ResetGuard;
81 impl Drop for ResetGuard {
82 fn drop(&mut self) {
83 FORCE_LINUX_CHECKED_NUMERIC.store(false, Ordering::SeqCst);
84 }
85 }
86 FORCE_LINUX_CHECKED_NUMERIC.store(true, Ordering::SeqCst);
87 let _guard = ResetGuard;
88 f()
89 }
90 #[cfg(not(target_os = "linux"))]
91 {
92 f()
93 }
94}
95
96pub struct ProcessHandle {
107 pid: u32,
108 start_identity: String,
109 binding: SignalBinding,
110 exited: AtomicBool,
111 closed: AtomicBool,
112 inner: imp::PlatformProcessHandle,
113}
114
115impl fmt::Debug for ProcessHandle {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.debug_struct("ProcessHandle")
118 .field("pid", &self.pid)
119 .field("start_identity", &self.start_identity)
120 .field("binding", &self.binding)
121 .field("exited", &self.exited.load(Ordering::Relaxed))
122 .field("closed", &self.closed.load(Ordering::Relaxed))
123 .finish_non_exhaustive()
124 }
125}
126
127impl ProcessHandle {
128 pub fn open(pid: u32) -> SysprimsResult<Self> {
139 Self::open_inner(pid, None)
140 }
141
142 pub fn open_verified(pid: u32, expected_start_identity: &str) -> SysprimsResult<Self> {
148 let trimmed = expected_start_identity.trim();
149 if trimmed.is_empty() {
150 return Err(SysprimsError::invalid_argument(
151 "expected_start_identity must not be empty",
152 ));
153 }
154 Self::open_inner(pid, Some(trimmed))
155 }
156
157 fn open_inner(pid: u32, expected_start_identity: Option<&str>) -> SysprimsResult<Self> {
158 validate_pid(pid)?;
159 let (start_identity, binding, inner) =
160 imp::open_platform_handle(pid, expected_start_identity)?;
161 Ok(Self {
162 pid,
163 start_identity,
164 binding,
165 exited: AtomicBool::new(false),
166 closed: AtomicBool::new(false),
167 inner,
168 })
169 }
170
171 pub const fn pid(&self) -> u32 {
173 self.pid
174 }
175
176 pub fn start_identity(&self) -> &str {
180 &self.start_identity
181 }
182
183 pub const fn binding(&self) -> SignalBinding {
185 self.binding
186 }
187
188 pub fn is_closed(&self) -> bool {
190 self.closed.load(Ordering::Acquire)
191 }
192
193 fn ensure_open(&self) -> SysprimsResult<()> {
194 if self.is_closed() {
195 return Err(SysprimsError::invalid_argument("process handle is closed"));
196 }
197 Ok(())
198 }
199
200 pub fn exited(&self) -> SysprimsResult<bool> {
206 self.ensure_open()?;
207 if self.exited.load(Ordering::Acquire) {
208 return Ok(true);
209 }
210 let now_exited = self.inner.check_exited(self.pid, &self.start_identity)?;
211 if now_exited {
212 self.exited.store(true, Ordering::Release);
213 }
214 Ok(now_exited)
215 }
216
217 pub fn signal(&self, sig: i32) -> SysprimsResult<SignalBinding> {
223 self.ensure_open()?;
224 if self.exited()? {
225 return Err(SysprimsError::not_found(self.pid));
226 }
227 match self.inner.send_signal(self.pid, &self.start_identity, sig) {
228 Ok(binding) => Ok(binding),
229 Err(SysprimsError::NotFound { pid }) => {
230 self.exited.store(true, Ordering::Release);
231 Err(SysprimsError::NotFound { pid })
232 }
233 Err(err) => Err(err),
234 }
235 }
236
237 pub fn signal_by_name(&self, signal_name: &str) -> SysprimsResult<SignalBinding> {
240 let sig = resolve_signal_name(signal_name)?;
241 self.signal(sig)
242 }
243
244 pub fn terminate(&self) -> SysprimsResult<SignalBinding> {
246 self.signal(TERMINATE_SIGNAL)
247 }
248
249 pub fn force_kill(&self) -> SysprimsResult<SignalBinding> {
251 self.signal(FORCE_KILL_SIGNAL)
252 }
253
254 pub fn close(&self) {
256 if !self.closed.swap(true, Ordering::AcqRel) {
257 self.inner.close_handle();
258 }
259 }
260}
261
262impl Drop for ProcessHandle {
263 fn drop(&mut self) {
264 self.close();
265 }
266}
267
268pub fn open_process_handle(pid: u32) -> SysprimsResult<ProcessHandle> {
270 ProcessHandle::open(pid)
271}
272
273pub fn open_process_handle_verified(
276 pid: u32,
277 expected_start_identity: &str,
278) -> SysprimsResult<ProcessHandle> {
279 ProcessHandle::open_verified(pid, expected_start_identity)
280}
281
282#[cfg(target_os = "macos")]
287mod imp {
288 use std::io;
289 use std::ptr;
290 use std::sync::atomic::{AtomicI32, Ordering};
291
292 use libc::{c_int, c_void};
293 use sysprims_core::{SysprimsError, SysprimsResult};
294
295 use super::SignalBinding;
296
297 const KINFO_PROC_SIZE_64: usize = 648;
298 const OFF_P_STARTTIME_SEC: usize = 0;
299 const OFF_P_STARTTIME_USEC: usize = 8;
300 const OFF_P_STAT: usize = 36;
301 const OFF_P_PID: usize = 40;
302
303 const SIDL: u8 = 1;
304 const SRUN: u8 = 2;
305 const SSLEEP: u8 = 3;
306 const SSTOP: u8 = 4;
307 const SZOMB: u8 = 5;
308
309 pub(super) struct PlatformProcessHandle {
310 kq_fd: AtomicI32,
311 }
312
313 fn close_raw_fd(fd: c_int) {
314 if fd >= 0 {
315 unsafe {
316 let _ = libc::close(fd);
317 }
318 }
319 }
320
321 fn last_errno() -> i32 {
322 io::Error::last_os_error()
323 .raw_os_error()
324 .unwrap_or(libc::EIO)
325 }
326
327 fn read_kinfo_start_identity(pid: u32, op: &str) -> SysprimsResult<(String, bool)> {
329 let mut mib: [c_int; 4] = [
330 libc::CTL_KERN,
331 libc::KERN_PROC,
332 libc::KERN_PROC_PID,
333 pid as c_int,
334 ];
335 let mut buf = [0u8; KINFO_PROC_SIZE_64];
336 let mut size = buf.len();
337 let rc = unsafe {
338 libc::sysctl(
339 mib.as_mut_ptr(),
340 4,
341 buf.as_mut_ptr() as *mut c_void,
342 &mut size,
343 ptr::null_mut(),
344 0,
345 )
346 };
347 if rc != 0 {
348 let errno = last_errno();
349 return match errno {
350 libc::ESRCH => Err(SysprimsError::not_found(pid)),
351 libc::EPERM | libc::EACCES => Err(SysprimsError::permission_denied(pid, op)),
352 _ => Err(SysprimsError::system("sysctl(KERN_PROC_PID) failed", errno)),
353 };
354 }
355 if size == 0 {
356 return Err(SysprimsError::not_found(pid));
357 }
358 if size != KINFO_PROC_SIZE_64 {
359 return Err(SysprimsError::system(
360 "unexpected kinfo_proc size",
361 libc::EINVAL,
362 ));
363 }
364
365 let tv_sec = i64::from_ne_bytes(
366 buf[OFF_P_STARTTIME_SEC..OFF_P_STARTTIME_SEC + 8]
367 .try_into()
368 .unwrap(),
369 );
370 let tv_usec = i32::from_ne_bytes(
371 buf[OFF_P_STARTTIME_USEC..OFF_P_STARTTIME_USEC + 4]
372 .try_into()
373 .unwrap(),
374 );
375 let p_stat = buf[OFF_P_STAT];
376 let p_pid = i32::from_ne_bytes(buf[OFF_P_PID..OFF_P_PID + 4].try_into().unwrap());
377
378 if p_pid != (pid as i32) {
379 return Err(SysprimsError::not_found(pid));
380 }
381 if tv_sec < 0 || !(0..=999_999).contains(&tv_usec) {
382 return Err(SysprimsError::system(
383 "invalid kinfo_proc p_starttime",
384 libc::EINVAL,
385 ));
386 }
387
388 let is_zombie = match p_stat {
389 SZOMB => true,
390 SRUN | SSLEEP | SSTOP => false,
391 SIDL => return Err(SysprimsError::not_found(pid)),
392 _ => {
393 return Err(SysprimsError::system(
394 "unexpected kinfo_proc p_stat",
395 libc::EINVAL,
396 ))
397 }
398 };
399
400 Ok((format!("{tv_sec}.{tv_usec:06}"), is_zombie))
401 }
402
403 pub(super) fn open_platform_handle(
404 pid: u32,
405 expected_start_identity: Option<&str>,
406 ) -> SysprimsResult<(String, SignalBinding, PlatformProcessHandle)> {
407 let (birth0, zombie0) = read_kinfo_start_identity(pid, "open_process_handle")?;
408 if zombie0 {
409 return Err(SysprimsError::not_found(pid));
410 }
411 if let Some(expected) = expected_start_identity {
412 if birth0 != expected {
413 return Err(SysprimsError::not_found(pid));
414 }
415 }
416
417 let kill0 = unsafe { libc::kill(pid as c_int, 0) };
420 if kill0 != 0 {
421 let errno = last_errno();
422 return match errno {
423 libc::ESRCH => Err(SysprimsError::not_found(pid)),
424 libc::EPERM | libc::EACCES => {
425 Err(SysprimsError::permission_denied(pid, "open_process_handle"))
426 }
427 _ => Err(SysprimsError::system("kill(pid, 0) failed", errno)),
428 };
429 }
430
431 let kq = unsafe { libc::kqueue() };
432 if kq < 0 {
433 let errno = last_errno();
434 return Err(SysprimsError::system("kqueue() failed", errno));
435 }
436 if unsafe { libc::fcntl(kq, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 {
437 let errno = last_errno();
438 close_raw_fd(kq);
439 return Err(SysprimsError::system("fcntl(FD_CLOEXEC) failed", errno));
440 }
441
442 let change = libc::kevent {
443 ident: pid as libc::uintptr_t,
444 filter: libc::EVFILT_PROC,
445 flags: libc::EV_ADD | libc::EV_ENABLE | libc::EV_ONESHOT,
446 fflags: libc::NOTE_EXIT,
447 data: 0,
448 udata: ptr::null_mut(),
449 };
450 let mut out_ev: libc::kevent = unsafe { std::mem::zeroed() };
451 let zero_ts = libc::timespec {
452 tv_sec: 0,
453 tv_nsec: 0,
454 };
455 let n = loop {
456 let rc = unsafe { libc::kevent(kq, &change, 1, &mut out_ev, 1, &zero_ts) };
457 if rc >= 0 {
458 break rc;
459 }
460 let errno = last_errno();
461 if errno == libc::EINTR {
462 continue;
463 }
464 close_raw_fd(kq);
465 return match errno {
466 libc::ESRCH => Err(SysprimsError::not_found(pid)),
467 libc::EPERM | libc::EACCES => {
468 Err(SysprimsError::permission_denied(pid, "open_process_handle"))
469 }
470 _ => Err(SysprimsError::system("kevent registration failed", errno)),
471 };
472 };
473
474 if n > 0 {
475 if (out_ev.flags & libc::EV_ERROR) != 0 {
476 let err_code = out_ev.data as i32;
477 close_raw_fd(kq);
478 return match err_code {
479 libc::ESRCH => Err(SysprimsError::not_found(pid)),
480 libc::EPERM | libc::EACCES => {
481 Err(SysprimsError::permission_denied(pid, "open_process_handle"))
482 }
483 _ => Err(SysprimsError::system(
484 "kevent registration EV_ERROR",
485 err_code,
486 )),
487 };
488 }
489 if (out_ev.fflags & libc::NOTE_EXIT) != 0 {
490 close_raw_fd(kq);
491 return Err(SysprimsError::not_found(pid));
492 }
493 }
494
495 let (birth1, zombie1) = match read_kinfo_start_identity(pid, "open_process_handle") {
498 Ok(v) => v,
499 Err(err) => {
500 close_raw_fd(kq);
501 return Err(err);
502 }
503 };
504 if zombie1 || birth1 != birth0 {
505 close_raw_fd(kq);
506 return Err(SysprimsError::not_found(pid));
507 }
508
509 Ok((
510 birth0,
511 SignalBinding::CheckedNumeric,
512 PlatformProcessHandle {
513 kq_fd: AtomicI32::new(kq),
514 },
515 ))
516 }
517
518 impl PlatformProcessHandle {
519 pub(super) fn close_handle(&self) {
520 let fd = self.kq_fd.swap(-1, Ordering::AcqRel);
521 close_raw_fd(fd);
522 }
523
524 pub(super) fn check_exited(&self, pid: u32, start_identity: &str) -> SysprimsResult<bool> {
525 let kq = self.kq_fd.load(Ordering::Acquire);
526 if kq < 0 {
527 return Err(SysprimsError::invalid_argument("process handle is closed"));
528 }
529
530 let zero_ts = libc::timespec {
531 tv_sec: 0,
532 tv_nsec: 0,
533 };
534 loop {
535 let mut ev: libc::kevent = unsafe { std::mem::zeroed() };
536 let rc = unsafe { libc::kevent(kq, ptr::null(), 0, &mut ev, 1, &zero_ts) };
537 if rc > 0 {
538 if (ev.flags & libc::EV_ERROR) != 0 {
539 return Err(SysprimsError::system(
540 "kevent poll EV_ERROR",
541 ev.data as i32,
542 ));
543 }
544 if (ev.fflags & libc::NOTE_EXIT) != 0 {
545 return Ok(true);
546 }
547 break;
548 }
549 if rc == 0 {
550 break;
551 }
552 let errno = last_errno();
553 if errno == libc::EINTR {
554 continue;
555 }
556 return Err(SysprimsError::system("kevent poll failed", errno));
557 }
558
559 match read_kinfo_start_identity(pid, "exited") {
563 Ok((birth, is_zombie)) => Ok(is_zombie || birth != start_identity),
564 Err(SysprimsError::NotFound { .. }) => Ok(true),
565 Err(err) => Err(err),
566 }
567 }
568
569 pub(super) fn send_signal(
570 &self,
571 pid: u32,
572 start_identity: &str,
573 sig: i32,
574 ) -> SysprimsResult<SignalBinding> {
575 match read_kinfo_start_identity(pid, "signal") {
577 Ok((birth, is_zombie)) => {
578 if is_zombie || birth != start_identity {
579 return Err(SysprimsError::not_found(pid));
580 }
581 }
582 Err(SysprimsError::NotFound { .. }) => return Err(SysprimsError::not_found(pid)),
583 Err(err) => return Err(err),
584 }
585
586 crate::unix::kill_impl(pid, sig)?;
587 Ok(SignalBinding::CheckedNumeric)
588 }
589 }
590}
591
592#[cfg(target_os = "linux")]
593mod imp {
594 use std::fs::OpenOptions;
595 use std::io::{self, Read};
596 use std::os::unix::fs::OpenOptionsExt;
597 use std::ptr;
598 use std::sync::atomic::{AtomicI32, Ordering};
599
600 use libc::c_int;
601 use sysprims_core::{SysprimsError, SysprimsResult};
602
603 use super::{SignalBinding, FORCE_LINUX_CHECKED_NUMERIC};
604
605 pub(super) struct PlatformProcessHandle {
606 pidfd: AtomicI32,
610 bound: bool,
611 }
612
613 fn close_raw_fd(fd: c_int) {
614 if fd >= 0 {
615 unsafe {
616 let _ = libc::close(fd);
617 }
618 }
619 }
620
621 fn last_errno() -> i32 {
622 io::Error::last_os_error()
623 .raw_os_error()
624 .unwrap_or(libc::EIO)
625 }
626
627 #[derive(Debug, Clone, PartialEq, Eq)]
628 struct LinuxStatSnapshot {
629 start_ticks: String,
630 state: char,
631 num_threads: u64,
632 }
633
634 impl LinuxStatSnapshot {
635 fn is_whole_process_dead(&self) -> bool {
636 matches!(self.state, 'X' | 'x') || (self.state == 'Z' && self.num_threads <= 1)
637 }
638 }
639
640 fn parse_proc_stat_snapshot(stat_text: &str) -> Option<LinuxStatSnapshot> {
641 let (_, after_comm) = stat_text.rsplit_once(") ")?;
642 let mut fields = after_comm.split_whitespace();
643 let state = fields.next()?.chars().next()?;
644 let num_threads_str = fields.nth(16)?;
647 let num_threads = num_threads_str.parse::<u64>().ok()?;
648 let start_ticks_str = fields.nth(1)?;
650 let _ticks = start_ticks_str.parse::<u64>().ok()?;
651 Some(LinuxStatSnapshot {
652 start_ticks: start_ticks_str.to_string(),
653 state,
654 num_threads,
655 })
656 }
657
658 fn read_linux_stat(pid: u32, op: &str) -> SysprimsResult<LinuxStatSnapshot> {
659 let path = format!("/proc/{pid}/stat");
660 let mut file = OpenOptions::new()
661 .read(true)
662 .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW)
663 .open(&path)
664 .map_err(|err| match err.raw_os_error() {
665 Some(libc::ENOENT | libc::ESRCH) => SysprimsError::not_found(pid),
666 Some(libc::EPERM | libc::EACCES) => SysprimsError::permission_denied(pid, op),
667 Some(errno) => SysprimsError::system("open(/proc/<pid>/stat) failed", errno),
668 None => SysprimsError::system("open(/proc/<pid>/stat) failed", libc::EIO),
669 })?;
670
671 let mut buf = String::with_capacity(512);
672 file.read_to_string(&mut buf)
673 .map_err(|err| match err.raw_os_error() {
674 Some(libc::ENOENT | libc::ESRCH) => SysprimsError::not_found(pid),
675 Some(libc::EPERM | libc::EACCES) => SysprimsError::permission_denied(pid, op),
676 Some(errno) => SysprimsError::system("read(/proc/<pid>/stat) failed", errno),
677 None => SysprimsError::system("read(/proc/<pid>/stat) failed", libc::EIO),
678 })?;
679
680 parse_proc_stat_snapshot(&buf).ok_or_else(|| {
681 SysprimsError::system("malformed /proc/<pid>/stat payload", libc::EINVAL)
682 })
683 }
684
685 fn poll_pidfd_exited(fd: c_int) -> SysprimsResult<bool> {
686 loop {
687 let mut pfd = libc::pollfd {
688 fd,
689 events: libc::POLLIN,
690 revents: 0,
691 };
692 let rc = unsafe { libc::poll(&mut pfd, 1, 0) };
693 if rc > 0 {
694 if (pfd.revents & libc::POLLNVAL) != 0 {
695 return Err(SysprimsError::system("poll(pidfd) POLLNVAL", libc::EBADF));
696 }
697 if (pfd.revents & (libc::POLLIN | libc::POLLHUP)) != 0 {
698 return Ok(true);
699 }
700 if (pfd.revents & libc::POLLERR) != 0 {
701 return Err(SysprimsError::system("poll(pidfd) POLLERR", libc::EIO));
702 }
703 return Ok(false);
704 }
705 if rc == 0 {
706 return Ok(false);
707 }
708 let errno = last_errno();
709 if errno == libc::EINTR {
710 continue;
711 }
712 return Err(SysprimsError::system("poll(pidfd) failed", errno));
713 }
714 }
715
716 pub(super) fn open_platform_handle(
717 pid: u32,
718 expected_start_identity: Option<&str>,
719 ) -> SysprimsResult<(String, SignalBinding, PlatformProcessHandle)> {
720 let snap0 = read_linux_stat(pid, "open_process_handle")?;
721 if snap0.is_whole_process_dead() {
722 return Err(SysprimsError::not_found(pid));
723 }
724 if let Some(expected) = expected_start_identity {
725 if snap0.start_ticks != expected {
726 return Err(SysprimsError::not_found(pid));
727 }
728 }
729
730 let kill0 = unsafe { libc::kill(pid as c_int, 0) };
733 if kill0 != 0 {
734 let errno = last_errno();
735 return match errno {
736 libc::ESRCH => Err(SysprimsError::not_found(pid)),
737 libc::EPERM | libc::EACCES => {
738 Err(SysprimsError::permission_denied(pid, "open_process_handle"))
739 }
740 _ => Err(SysprimsError::system("kill(pid, 0) failed", errno)),
741 };
742 }
743
744 let force_fallback = FORCE_LINUX_CHECKED_NUMERIC.load(Ordering::SeqCst);
745 let (pidfd, binding) = if force_fallback {
746 if snap0.state == 'Z' {
747 return Err(SysprimsError::not_found(pid));
748 }
749 (-1, SignalBinding::CheckedNumeric)
750 } else {
751 let raw_fd = loop {
752 let rc = unsafe { libc::syscall(libc::SYS_pidfd_open, pid as c_int, 0u32) };
753 if rc >= 0 {
754 break rc as c_int;
755 }
756 let errno = last_errno();
757 if errno == libc::EINTR {
758 continue;
759 }
760 if errno == libc::ENOSYS {
761 break -1;
762 }
763 return match errno {
764 libc::ESRCH => Err(SysprimsError::not_found(pid)),
765 libc::EPERM | libc::EACCES => {
766 Err(SysprimsError::permission_denied(pid, "open_process_handle"))
767 }
768 _ => Err(SysprimsError::system("pidfd_open failed", errno)),
769 };
770 };
771
772 if raw_fd >= 0 {
773 if unsafe { libc::fcntl(raw_fd, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 {
774 let errno = last_errno();
775 close_raw_fd(raw_fd);
776 return Err(SysprimsError::system("fcntl(FD_CLOEXEC) failed", errno));
777 }
778 match poll_pidfd_exited(raw_fd) {
782 Ok(true) => {
783 close_raw_fd(raw_fd);
784 return Err(SysprimsError::not_found(pid));
785 }
786 Ok(false) => {}
787 Err(err) => {
788 close_raw_fd(raw_fd);
789 return Err(err);
790 }
791 }
792 (raw_fd, SignalBinding::Bound)
793 } else {
794 if snap0.state == 'Z' {
795 return Err(SysprimsError::not_found(pid));
796 }
797 (-1, SignalBinding::CheckedNumeric)
798 }
799 };
800
801 let snap1 = match read_linux_stat(pid, "open_process_handle") {
804 Ok(s) => s,
805 Err(err) => {
806 close_raw_fd(pidfd);
807 return Err(err);
808 }
809 };
810 if snap1.start_ticks != snap0.start_ticks || snap1.is_whole_process_dead() {
811 close_raw_fd(pidfd);
812 return Err(SysprimsError::not_found(pid));
813 }
814 if pidfd >= 0 {
815 if let Ok(true) = poll_pidfd_exited(pidfd) {
816 close_raw_fd(pidfd);
817 return Err(SysprimsError::not_found(pid));
818 }
819 }
820
821 Ok((
822 snap0.start_ticks,
823 binding,
824 PlatformProcessHandle {
825 pidfd: AtomicI32::new(pidfd),
826 bound: binding == SignalBinding::Bound,
827 },
828 ))
829 }
830
831 impl PlatformProcessHandle {
832 pub(super) fn close_handle(&self) {
833 let fd = self.pidfd.swap(-1, Ordering::AcqRel);
834 close_raw_fd(fd);
835 }
836
837 pub(super) fn check_exited(&self, pid: u32, start_identity: &str) -> SysprimsResult<bool> {
838 if self.bound {
839 let fd = self.pidfd.load(Ordering::Acquire);
840 if fd < 0 {
841 return Err(SysprimsError::invalid_argument("process handle is closed"));
842 }
843 return poll_pidfd_exited(fd);
844 }
845
846 match read_linux_stat(pid, "exited") {
847 Ok(snap) => Ok(snap.is_whole_process_dead() || snap.start_ticks != start_identity),
848 Err(SysprimsError::NotFound { .. }) => Ok(true),
849 Err(err) => Err(err),
850 }
851 }
852
853 pub(super) fn send_signal(
854 &self,
855 pid: u32,
856 start_identity: &str,
857 sig: i32,
858 ) -> SysprimsResult<SignalBinding> {
859 if self.bound {
860 let fd = self.pidfd.load(Ordering::Acquire);
861 if fd < 0 {
862 return Err(SysprimsError::invalid_argument("process handle is closed"));
863 }
864 loop {
865 let rc = unsafe {
866 libc::syscall(
867 libc::SYS_pidfd_send_signal,
868 fd,
869 sig,
870 ptr::null::<libc::siginfo_t>(),
871 0u32,
872 )
873 };
874 if rc == 0 {
875 return Ok(SignalBinding::Bound);
876 }
877 let errno = last_errno();
878 if errno == libc::EINTR {
879 continue;
880 }
881 return match errno {
882 libc::ESRCH => Err(SysprimsError::not_found(pid)),
883 libc::EPERM | libc::EACCES => {
884 Err(SysprimsError::permission_denied(pid, "signal"))
885 }
886 libc::EINVAL => Err(SysprimsError::invalid_argument(format!(
887 "invalid signal: {sig}"
888 ))),
889 _ => Err(SysprimsError::system("pidfd_send_signal failed", errno)),
890 };
891 }
892 }
893
894 match read_linux_stat(pid, "signal") {
897 Ok(snap) => {
898 if snap.is_whole_process_dead() || snap.start_ticks != start_identity {
899 return Err(SysprimsError::not_found(pid));
900 }
901 }
902 Err(SysprimsError::NotFound { .. }) => return Err(SysprimsError::not_found(pid)),
903 Err(err) => return Err(err),
904 }
905
906 crate::unix::kill_impl(pid, sig)?;
907 Ok(SignalBinding::CheckedNumeric)
908 }
909 }
910}
911
912#[cfg(target_os = "windows")]
913mod imp {
914 use std::sync::atomic::{AtomicIsize, Ordering};
915
916 use sysprims_core::{SysprimsError, SysprimsResult};
917 use windows_sys::Win32::Foundation::{
918 CloseHandle, GetLastError, SetHandleInformation, ERROR_ACCESS_DENIED,
919 ERROR_INVALID_PARAMETER, HANDLE, HANDLE_FLAG_INHERIT, WAIT_OBJECT_0,
920 };
921 use windows_sys::Win32::System::Console::{GenerateConsoleCtrlEvent, CTRL_C_EVENT};
922 use windows_sys::Win32::System::Threading::{
923 GetProcessTimes, OpenProcess, TerminateProcess, WaitForSingleObject,
924 PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
925 };
926
927 use super::SignalBinding;
928
929 pub(super) struct PlatformProcessHandle {
930 handle: AtomicIsize,
931 }
932
933 fn close_raw_handle(raw: isize) {
934 if raw != 0 {
935 unsafe {
936 let _ = CloseHandle(raw as HANDLE);
937 }
938 }
939 }
940
941 fn read_handle_creation_time(handle: HANDLE, pid: u32) -> SysprimsResult<String> {
942 let mut creation = unsafe { std::mem::zeroed() };
943 let mut exit = unsafe { std::mem::zeroed() };
944 let mut kernel = unsafe { std::mem::zeroed() };
945 let mut user = unsafe { std::mem::zeroed() };
946 let ok =
947 unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) };
948 if ok == 0 {
949 let err = unsafe { GetLastError() };
950 return match err {
951 ERROR_ACCESS_DENIED => {
952 Err(SysprimsError::permission_denied(pid, "open_process_handle"))
953 }
954 ERROR_INVALID_PARAMETER => Err(SysprimsError::not_found(pid)),
955 _ => Err(SysprimsError::system("GetProcessTimes failed", err as i32)),
956 };
957 }
958 let ticks = ((creation.dwHighDateTime as u64) << 32) | (creation.dwLowDateTime as u64);
959 Ok(ticks.to_string())
960 }
961
962 fn read_pid_creation_time(pid: u32, op: &str) -> SysprimsResult<String> {
963 let h = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
964 if h.is_null() {
965 let err = unsafe { GetLastError() };
966 return match err {
967 ERROR_ACCESS_DENIED => Err(SysprimsError::permission_denied(pid, op)),
968 ERROR_INVALID_PARAMETER => Err(SysprimsError::not_found(pid)),
969 _ => Err(SysprimsError::system("OpenProcess failed", err as i32)),
970 };
971 }
972 let res = read_handle_creation_time(h, pid);
973 unsafe {
974 let _ = CloseHandle(h);
975 }
976 res
977 }
978
979 pub(super) fn open_platform_handle(
980 pid: u32,
981 expected_start_identity: Option<&str>,
982 ) -> SysprimsResult<(String, SignalBinding, PlatformProcessHandle)> {
983 let birth0 = read_pid_creation_time(pid, "open_process_handle")?;
984 if let Some(expected) = expected_start_identity {
985 if birth0 != expected {
986 return Err(SysprimsError::not_found(pid));
987 }
988 }
989
990 let access = PROCESS_TERMINATE | PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION;
991 let handle = unsafe { OpenProcess(access, 0, pid) };
992 if handle.is_null() {
993 let err = unsafe { GetLastError() };
994 return match err {
995 ERROR_ACCESS_DENIED => {
996 Err(SysprimsError::permission_denied(pid, "open_process_handle"))
997 }
998 ERROR_INVALID_PARAMETER => Err(SysprimsError::not_found(pid)),
999 _ => Err(SysprimsError::system("OpenProcess failed", err as i32)),
1000 };
1001 }
1002 unsafe {
1003 let _ = SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
1004 }
1005
1006 let handle_birth = match read_handle_creation_time(handle, pid) {
1007 Ok(b) => b,
1008 Err(err) => {
1009 unsafe {
1010 let _ = CloseHandle(handle);
1011 }
1012 return Err(err);
1013 }
1014 };
1015 let wait_rc = unsafe { WaitForSingleObject(handle, 0) };
1016 if wait_rc == WAIT_OBJECT_0 || handle_birth != birth0 {
1017 unsafe {
1018 let _ = CloseHandle(handle);
1019 }
1020 return Err(SysprimsError::not_found(pid));
1021 }
1022
1023 let birth1 = match read_pid_creation_time(pid, "open_process_handle") {
1025 Ok(b) => b,
1026 Err(err) => {
1027 unsafe {
1028 let _ = CloseHandle(handle);
1029 }
1030 return Err(err);
1031 }
1032 };
1033 if birth1 != birth0 {
1034 unsafe {
1035 let _ = CloseHandle(handle);
1036 }
1037 return Err(SysprimsError::not_found(pid));
1038 }
1039
1040 Ok((
1041 birth0,
1042 SignalBinding::Bound,
1043 PlatformProcessHandle {
1044 handle: AtomicIsize::new(handle as isize),
1045 },
1046 ))
1047 }
1048
1049 impl PlatformProcessHandle {
1050 pub(super) fn close_handle(&self) {
1051 let raw = self.handle.swap(0, Ordering::AcqRel);
1052 close_raw_handle(raw);
1053 }
1054
1055 pub(super) fn check_exited(
1056 &self,
1057 _pid: u32,
1058 _start_identity: &str,
1059 ) -> SysprimsResult<bool> {
1060 let raw = self.handle.load(Ordering::Acquire);
1061 if raw == 0 {
1062 return Err(SysprimsError::invalid_argument("process handle is closed"));
1063 }
1064 let rc = unsafe { WaitForSingleObject(raw as HANDLE, 0) };
1065 Ok(rc == WAIT_OBJECT_0)
1066 }
1067
1068 pub(super) fn send_signal(
1069 &self,
1070 pid: u32,
1071 start_identity: &str,
1072 sig: i32,
1073 ) -> SysprimsResult<SignalBinding> {
1074 let raw = self.handle.load(Ordering::Acquire);
1075 if raw == 0 {
1076 return Err(SysprimsError::invalid_argument("process handle is closed"));
1077 }
1078 let handle = raw as HANDLE;
1079 if unsafe { WaitForSingleObject(handle, 0) } == WAIT_OBJECT_0 {
1080 return Err(SysprimsError::not_found(pid));
1081 }
1082
1083 match sig {
1084 rsfulmen::foundry::signals::SIGTERM | rsfulmen::foundry::signals::SIGKILL => {
1085 let ok = unsafe { TerminateProcess(handle, 1) };
1086 if ok != 0 {
1087 Ok(SignalBinding::Bound)
1088 } else {
1089 let err = unsafe { GetLastError() };
1090 if unsafe { WaitForSingleObject(handle, 0) } == WAIT_OBJECT_0 {
1091 return Err(SysprimsError::not_found(pid));
1092 }
1093 Err(SysprimsError::system("TerminateProcess failed", err as i32))
1094 }
1095 }
1096 rsfulmen::foundry::signals::SIGINT => {
1097 let current_birth = read_pid_creation_time(pid, "signal")?;
1098 if current_birth != start_identity {
1099 return Err(SysprimsError::not_found(pid));
1100 }
1101 let ok = unsafe { GenerateConsoleCtrlEvent(CTRL_C_EVENT, pid) };
1102 if ok != 0 {
1103 Ok(SignalBinding::CheckedNumeric)
1104 } else {
1105 let err = unsafe { GetLastError() };
1106 match err {
1107 ERROR_ACCESS_DENIED => {
1108 Err(SysprimsError::permission_denied(pid, "signal"))
1109 }
1110 ERROR_INVALID_PARAMETER => Err(SysprimsError::not_found(pid)),
1111 _ => Err(SysprimsError::system(
1112 "GenerateConsoleCtrlEvent failed",
1113 err as i32,
1114 )),
1115 }
1116 }
1117 }
1118 _ => Err(SysprimsError::not_supported(
1119 format!("signal {sig}"),
1120 "windows",
1121 )),
1122 }
1123 }
1124 }
1125}
1126
1127#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
1128mod imp {
1129 use sysprims_core::{SysprimsError, SysprimsResult};
1130
1131 use super::SignalBinding;
1132
1133 pub(super) struct PlatformProcessHandle;
1134
1135 pub(super) fn open_platform_handle(
1136 _pid: u32,
1137 _expected_start_identity: Option<&str>,
1138 ) -> SysprimsResult<(String, SignalBinding, PlatformProcessHandle)> {
1139 Err(SysprimsError::not_supported(
1140 "open_process_handle",
1141 std::env::consts::OS,
1142 ))
1143 }
1144
1145 impl PlatformProcessHandle {
1146 pub(super) fn close_handle(&self) {}
1147
1148 pub(super) fn check_exited(
1149 &self,
1150 _pid: u32,
1151 _start_identity: &str,
1152 ) -> SysprimsResult<bool> {
1153 Err(SysprimsError::not_supported(
1154 "open_process_handle",
1155 std::env::consts::OS,
1156 ))
1157 }
1158
1159 pub(super) fn send_signal(
1160 &self,
1161 _pid: u32,
1162 _start_identity: &str,
1163 _sig: i32,
1164 ) -> SysprimsResult<SignalBinding> {
1165 Err(SysprimsError::not_supported(
1166 "open_process_handle",
1167 std::env::consts::OS,
1168 ))
1169 }
1170 }
1171}