1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
//! Signal support for Unix-like systems.
//!
//! Signals in Unix are much more functional and versatile than ANSI C signals – there is simply much, much more of them. In addition to that, there is a special group of signals called "real-time signals" (more on those below).
//!
//! # Main signals
//! The [`SignalType`] enumeration provides all standard signals as defined in POSIX.1-2001. More signal types may be added later, which is why exhaustively matching on it is not possible. It can be cheaply converted to a 32-bit integer, though. See its documentation for more on conversions.
//!
//! The `set_handler` function is used to create an association between a `SignalType` and a signal handling strategy.
//!
//! # Real-time signals
//! In addition to usual signals, there's a special group of signals called "real-time signals". Those signals do not have fixed identifiers and are not generated by the system or kernel. Instead, they can only be sent between processes.
//!
//! # Signal-safe C functions
//! Very few C functions can be called from a signal handler. Allocating memory, using the thread API and manipulating interval timers, for example, is prohibited in a signal handler. Calling a function which is not signal safe results in undefined behavior, i.e. memory unsafety. Rather than excluding certain specific functions, the POSIX specification only speicifies functions which *are* signal-safe. The following C functions are guaranteed to be safe to call from a signal handler:
//! - `_Exit`
//! - `_exit`
//! - `abort`
//! - `accept`
//! - `access`
//! - `aio_error`
//! - `aio_return`
//! - `aio_suspend`
//! - `alarm`
//! - `bind`
//! - `cfgetispeed`
//! - `cfgetospeed`
//! - `cfsetispeed`
//! - `cfsetospeed`
//! - `chdir`
//! - `chmod`
//! - `chown`
//! - `clock_gettime`
//! - `close`
//! - `connect`
//! - `creat`
//! - `dup`
//! - `dup2`
//! - `execle`
//! - `execve`
//! - `fchmod`
//! - `fchown`
//! - `fcntl`
//! - `fdatasync`
//! - `fork`
//! - `fpathconf`
//! - `fstat`
//! - `fsync`
//! - `ftruncate`
//! - `getegid`
//! - `geteuid`
//! - `getgid`
//! - `getgroups`
//! - `getpeername`
//! - `getpgrp`
//! - `getpid`
//! - `getppid`
//! - `getsockname`
//! - `getsockopt`
//! - `getuid`
//! - `kill`
//! - `link`
//! - `listen`
//! - `lseek`
//! - `lstat`
//! - `mkdir`
//! - `mkfifo`
//! - `open`
//! - `pathconf`
//! - `pause`
//! - `pipe`
//! - `poll`
//! - `posix_trace_event`
//! - `pselect`
//! - `raise`
//! - `read`
//! - `readlink`
//! - `recv`
//! - `recvfrom`
//! - `recvmsg`
//! - `rename`
//! - `rmdir`
//! - `select`
//! - `sem_post`
//! - `send`
//! - `sendmsg`
//! - `sendto`
//! - `setgid`
//! - `setpgid`
//! - `setsid`
//! - `setsockopt`
//! - `setuid`
//! - `shutdown`
//! - `sigaction`
//! - `sigaddset`
//! - `sigdelset`
//! - `sigemptyset`
//! - `sigfillset`
//! - `sigismember`
//! - `signal`
//! - `sigpause`
//! - `sigpending`
//! - `sigprocmask`
//! - `sigqueue`
//! - `sigset`
//! - `sigsuspend`
//! - `sleep`
//! - `sockatmark`
//! - `socket`
//! - `socketpair`
//! - `stat`
//! - `symlink`
//! - `sysconf`
//! - `tcdrain`
//! - `tcflow`
//! - `tcflush`
//! - `tcgetattr`
//! - `tcgetpgrp`
//! - `tcsendbreak`
//! - `tcsetattr`
//! - `tcsetpgrp`
//! - `time`
//! - `timer_getoverrun`
//! - `timer_gettime`
//! - `timer_settime`
//! - `times`
//! - `umask`
//! - `uname`
//! - `unlink`
//! - `utime`
//! - `wait`
//! - `waitpid`
//! - `write`
//!
//! Many Rust crates, including the standard library, use signal-unsafe functions not on this list in safe code. For example, `Vec`, `Box` and `Rc`/`Arc` perform memory allocations, and `Mutex`/`RwLock` perform `pthread` calls. For this reason, creating a signal hook is an unsafe operation.
//!
//! [`SignalType`]: enum.SignalType.html " "
use super::imports::*;
use cfg_if::cfg_if;
use std::{
convert::{TryFrom, TryInto},
error::Error,
fmt::{self, Display, Formatter},
io,
mem::zeroed,
panic, process,
};
use to_method::To;
cfg_if! {
if #[cfg(any(
target_os = "linux",
target_os = "android",
))] {
// don't care about LinuxThreads lmao
const SIGRTMIN: i32 = 34;
const SIGRTMAX: i32 = 64;
} else if #[cfg(target_os = "freebsd")] {
const SIGRTMIN: i32 = 65;
const SIGRTMAX: i32 = 126;
} else if #[cfg(target_os = "netbsd")] {
const SIGRTMIN: i32 = 33;
const SIGRTMAX: i32 = 63;
} else if #[cfg(target_os = "redox")] {
const SIGRTMIN: i32 = 27;
const SIGRTMAX: i32 = 31;
} else {
const SIGRTMIN: i32 = 1; // min is smaller than max so that the sloppy calculation works
const SIGRTMAX: i32 = 0;
}
}
/// Whether real-time signals are supported at all.
///
/// The platforms for which `interprocess` has explicit support for real-time signals are:
/// - Linux
/// - includes Android
/// - FreeBSD
/// - NetBSD
/// - Redox
pub const REALTIME_SIGNALS_SUPPORTED: bool = NUM_REALTIME_SIGNALS != 0;
/// How many real-time signals are supported. Remember that real-time signals start from 0, so this number is higher than the highest possible real-time signal by 1.
///
/// Platform-specific values for this constant are:
/// - **Linux** and **NetBSD**: 31
/// - **FreeBSD**: 62
/// - **Redox**: 5 (does not conform with POSIX)
pub const NUM_REALTIME_SIGNALS: u32 = (SIGRTMAX - SIGRTMIN + 1) as u32;
/// Returns `true` if the specified signal is a valid real-time signal value, `false` otherwise.
#[allow(clippy::absurd_extreme_comparisons)] // For systems where there are no realtime signals
pub const fn is_valid_rtsignal(rtsignal: u32) -> bool {
rtsignal < NUM_REALTIME_SIGNALS
}
/// The first field is the current method of handling a specific signal, the second one is the flags which were set for it.
#[cfg(all(unix, feature = "signals"))]
type HandlerAndFlags = (SignalHandler, i32);
#[cfg(all(unix, feature = "signals"))]
static HANDLERS: Lazy<RwLock<IntMap<HandlerAndFlags>>> = Lazy::new(|| RwLock::new(IntMap::new()));
/// Installs the specified handler for the specified standard signal, using the default values for the flags.
///
/// See [`HandlerOptions`] builder if you'd like to customize the flags.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
///
/// let handler = unsafe {
/// // Since signal handlers are restricted to a specific set of C functions, creating a
/// // handler from an arbitrary function is unsafe because it might call a function
/// // outside the list, and there's no real way to know that at compile time with the
/// // current version of Rust. Since we're only using the write() system call here, this
/// // is safe.
/// SignalHandler::from_fn(|| {
/// println!("You pressed Ctrl-C!");
/// })
/// };
///
/// // Install our handler for the KeyboardInterrupt signal type.
/// signal::set_handler(SignalType::KeyboardInterrupt, handler)?;
/// # }
/// # Ok(()) }
/// ```
///
/// [`HandlerOptions`]: struct.HandlerOptions.html " "
pub fn set_handler(signal_type: SignalType, handler: SignalHandler) -> Result<(), SetHandlerError> {
HandlerOptions::for_signal(signal_type)
.set_new_handler(handler)
.set()
}
/// Installs the specified handler for the specified unsafe signal, using the default values for the flags.
///
/// See [`HandlerOptions`] builder if you'd like to customize the flags.
///
/// # Safety
/// See the [`set_unsafe`] safety notes.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
///
/// let handler = unsafe {
/// // Since signal handlers are restricted to a specific set of C functions, creating a
/// // handler from an arbitrary function is unsafe because it might call a function
/// // outside the list, and there's no real way to know that at compile time with the
/// // current version of Rust. Since we're only using the write() system call here, this
/// // is safe.
/// SignalHandler::from_fn(|| {
/// println!("Oh no, the motherboard broke!");
/// std::process::abort();
/// })
/// };
///
/// unsafe {
/// // Install our handler for the MemoryBusError signal type.
/// signal::set_unsafe_handler(SignalType::MemoryBusError, handler)?;
/// }
/// # }
/// # Ok(()) }
/// ```
///
/// [`HandlerOptions`]: struct.HandlerOptions.html " "
/// [`set_unsafe`]: struct.HandlerOptions.html#method.set_unsafe " "
pub unsafe fn set_unsafe_handler(
signal_type: SignalType,
handler: SignalHandler,
) -> Result<(), SetHandlerError> {
unsafe {
HandlerOptions::for_signal(signal_type)
.set_new_handler(handler)
.set_unsafe()
}
}
/// Installs the specified handler for the specified real-time signal, using the default values for the flags.
///
/// See [`HandlerOptions`] builder if you'd like to customize the flags.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalHandler};
///
/// let handler = unsafe {
/// // Since signal handlers are restricted to a specific set of C functions, creating a
/// // handler from an arbitrary function is unsafe because it might call a function
/// // outside the list, and there's no real way to know that at compile time with the
/// // current version of Rust. Since we're only using the write() system call here, this
/// // is safe.
/// SignalHandler::from_fn(|| {
/// println!("You sent a real-time signal!");
/// })
/// };
///
/// // Install our handler for the real-time signal 0.
/// signal::set_rthandler(0, handler)?;
/// # }
/// # Ok(()) }
/// ```
///
/// [`HandlerOptions`]: struct.HandlerOptions.html " "
pub fn set_rthandler(rtsignal: u32, handler: SignalHandler) -> Result<(), SetHandlerError> {
HandlerOptions::for_rtsignal(rtsignal)
.set_new_handler(handler)
.set()
}
unsafe fn install_hook(signum: i32, hook: usize, flags: i32) -> io::Result<()> {
let success = {
let [mut old_handler, mut new_handler] = unsafe {
// SAFETY: sigaction only consists of integers and therefore can
// contain an all-0 bit pattern
[zeroed::<sigaction>(); 2]
};
new_handler.sa_sigaction = hook;
new_handler.sa_flags = flags;
unsafe {
// SAFETY: all the pointers that are being passed come from references and only involve
// a single cast, which means that it's just a reference-to-pointer cast and not a
// pointer-to-pointer cast (the latter can cast any pointer to any other pointer, but
// you need two casts in order to convert a reference to a pointer to an arbitrary type)
libc::sigaction(signum, &new_handler as *const _, &mut old_handler as *mut _) != -1
}
};
if success {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// Options for installing a signal handler.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
///
/// let handler = unsafe {
/// // Since signal handlers are restricted to a specific set of C functions, creating a
/// // handler from an arbitrary function is unsafe because it might call a function
/// // outside the list, and there's no real way to know that at compile time with the
/// // current version of Rust. Since we're only using the write() system call here, this
/// // is safe.
/// SignalHandler::from_fn(|| {
/// println!("You pressed Ctrl-C!");
/// })
/// };
///
/// // Let's use the builder to customize the signal handler:
/// signal::HandlerOptions::for_signal(SignalType::KeyboardInterrupt)
/// .set_new_handler(handler)
/// .auto_reset_handler(true) // Let's remove the signal handler after it fires once.
/// .system_call_restart(false) // Avoid restarting system calls and let them fail with the
/// // Interrupted error type. There normally isn't a reason to
/// // do this, but for the sake of the example, let's assume
/// // that there is.
/// .set()?; // Finalize the builder by installing the handler.
/// # }
/// # Ok(()) }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[must_use = "the signal handler is attached by calling `.set()`, which consumes the builder"]
pub struct HandlerOptions {
signal: i32,
/// The handler to be set up. If `None`, the handler is not changed by the call.
pub handler: Option<SignalHandler>,
/// For the [`ChildProcessEvent`] signal, this option *disables* receiving the signal if it was generated because the child process was suspended (using any signal which suspends a process, such as [`Suspend`] or [`ForceSuspend`]) or [resumed][`Continue`].
///
/// If enabled on a signal which is not [`ChildProcessEvent`], a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
///
/// [`ChildProcessEvent`]: enum.SignalType.html#variant.ChildProcessEvent " "
/// [`Suspend`]: enum.SignalType.html#variant.Suspend " "
/// [`ForceSuspend`]: enum.SignalType.html#variant.ForceSuspend " "
/// [`Continue`]: enum.SignalType.html#variant.Continue " "
/// [`set`]: #method.set " "
pub ignore_child_stop_events: bool,
/// Allow the signal handler to interrupt a previous invocation of itself. If disabled, the signal handler will disable its own signal when called and restore previous state when it finishes executing. If not, an infinite amount of signals can be received on top of each other, which is likely a stack overflow risk.
///
/// If enabled but the handler is [set to use the default handling method][`Default`] from the OS, a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
///
/// [`Default`]: enum.SignalHandler.html#variant.Default " "
/// [`set`]: #method.set " "
pub recursive_handler: bool,
/// Automatically restart certain system calls instead of failing with the [`Interrupted`] error type. Some other system calls are not restarted with this function and may fail with [`Interrupted`] anyway. Consult your manual pages for more details.
///
/// [`Interrupted`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.Interrupted " "
pub system_call_restart: bool,
/// Automatically reset the handler to the default handling method whenever it is executed.
///
/// If enabled but the handler is [set to use the default handling method][`Default`] from the OS, a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
///
/// [`Default`]: enum.SignalHandler.html#variant.Default " "
/// [`set`]: #method.set " "
pub auto_reset_handler: bool,
}
impl HandlerOptions {
/// Creates a builder for a handler for the specified signal.
pub fn for_signal(signal: SignalType) -> Self {
Self {
signal: signal.into(),
handler: None,
ignore_child_stop_events: false,
recursive_handler: false,
system_call_restart: true,
auto_reset_handler: false,
}
}
/// Creates a builder for a handler for the specified real-time signal.
///
/// # Panics
/// Guaranteed to panic if the specified real-time signal is outside the range of real-time signals supported by the OS. See [`NUM_REALTIME_SIGNALS`].
///
/// [`NUM_REALTIME_SIGNALS`]: constant.NUM_REALTIME_SIGNALS.html " "
pub fn for_rtsignal(rtsignal: u32) -> Self {
assert!(
is_valid_rtsignal(rtsignal),
"invalid real-time signal value – check the NUM_REALTIME_SIGNALS constant to see how \
many are supported"
);
Self {
signal: rtsignal as i32,
handler: None,
ignore_child_stop_events: false,
recursive_handler: false,
system_call_restart: true,
auto_reset_handler: false,
}
}
/// Sets the handler for the signal to the specified value. If `None`, the old value is used.
pub fn set_new_handler(mut self, handler: impl Into<Option<SignalHandler>>) -> Self {
self.handler = handler.into();
self
}
/// Sets the [`ignore_child_stop_events`] flag to the specified value.
///
/// [`ignore_child_stop_events`]: #structfield.ignore_child_stop_events " "
pub fn ignore_child_stop_events(mut self, ignore: impl Into<bool>) -> Self {
self.ignore_child_stop_events = ignore.into();
self
}
/// Sets the [`recursive_handler`] flag to the specified value.
///
/// [`recursive_handler`]: #structfield.recursive_handler " "
pub fn recursive_handler(mut self, recursive: impl Into<bool>) -> Self {
self.recursive_handler = recursive.into();
self
}
/// Sets the [`system_call_restart`] flag to the specified value.
///
/// [`system_call_restart`]: #structfield.system_call_restart " "
pub fn system_call_restart(mut self, restart: impl Into<bool>) -> Self {
self.system_call_restart = restart.into();
self
}
/// Sets the [`auto_reset_handler`] flag to the specified value.
///
/// [`auto_reset_handler`]: #structfield.auto_reset_handler " "
pub fn auto_reset_handler(mut self, reset: impl Into<bool>) -> Self {
self.auto_reset_handler = reset.into();
self
}
/// Installs the signal handler.
pub fn set(self) -> Result<(), SetHandlerError> {
if let Ok(val) = SignalType::try_from(self.signal) {
if val.is_unsafe() {
return Err(SetHandlerError::UnsafeSignal);
}
}
unsafe { self.set_unsafe() }
}
/// Installs the signal handler, even if the signal being handled is unsafe.
///
/// # Safety
/// The handler and all code that may or may not execute afterwards must be prepared for the aftermath of what might've caused the signal.
///
/// [`SegmentationFault`] or [`BusError`] are most likely caused by undefined behavior invoked from Rust (the former is caused by dereferencing invalid memory, the latter is caused by dereferencing an incorrectly aligned pointer on ISAs like ARM which do not tolerate misaligned pointers), which means that the program is unsound and the only meaningful thing to do is to capture as much information as possible in a safe way – preferably using OS services to create a dump, rather than trying to read the program's global state, which might be irreversibly corrupted – and write the crash dump to some on-disk location.
///
/// [`SegmentationFault`]: enum.SignalType.html#variant.SegmentationFault " "
/// [`BusError`]: enum.SignalType.html#variant.BusError " "
pub unsafe fn set_unsafe(self) -> Result<(), SetHandlerError> {
if let Ok(val) = SignalType::try_from(self.signal) {
if val.is_unblockable() {
return Err(SetHandlerError::UnblockableSignal(val));
}
} else if !is_valid_rtsignal(self.signal as u32) {
return Err(SetHandlerError::RealTimeSignalOutOfBounds {
attempted: self.signal as u32,
max: NUM_REALTIME_SIGNALS,
});
}
let handlers = HANDLERS.read();
let new_flags = self.flags_as_i32();
let mut need_to_upgrade_handle = false;
let need_to_install_hook =
if let Some((existing_handler, existing_flags)) = handlers.get(self.signal as u64) {
// This signal's handler was set before – check if we need to install new flags or if
// one is default and another isn't, which would mean that either that no hook was
// installed and we have to install one or there was one installed but we need to
// install the default hook explicitly.
let new_handler = self.handler.unwrap_or_default();
if new_handler != *existing_handler || new_flags != *existing_flags {
need_to_upgrade_handle = true;
true
} else {
let one_handler_is_default_and_another_isnt = (new_handler.is_default()
&& !existing_handler.is_default())
|| (!new_handler.is_default() && existing_handler.is_default());
*existing_flags != new_flags || one_handler_is_default_and_another_isnt
}
} else {
need_to_upgrade_handle = true;
!self.handler.unwrap_or_default().is_default()
};
drop(handlers);
if need_to_upgrade_handle {
let mut handlers = HANDLERS.write();
let signal_u64 = self.signal as u64;
handlers.remove(signal_u64);
handlers.insert(signal_u64, (self.handler.unwrap_or_default(), new_flags));
}
if need_to_install_hook {
let hook_val = match self.handler.unwrap_or_default() {
SignalHandler::Default => SIG_DFL,
_ => signal_receiver as usize,
};
unsafe {
// SAFETY: we're using a correct value for the hook
install_hook(self.signal, hook_val, new_flags)?
}
}
Ok(())
}
fn flags_as_i32(self) -> i32 {
if self.handler.unwrap_or_default().is_default() {
debug_assert!(
!self.recursive_handler,
"cannot use the recursive_handler flag with the default handling method",
);
}
if self.signal != SIGCHLD {
debug_assert!(
!self.ignore_child_stop_events,
"\
cannot use the ignore_child_stop_events flag when the signal to be handled isn't \
ChildProcessEvent",
);
}
let mut flags = 0;
if self.auto_reset_handler {
flags |= SA_RESETHAND;
}
if self.ignore_child_stop_events {
flags |= SA_NOCLDSTOP;
}
if self.recursive_handler {
flags |= SA_NODEFER;
}
if self.system_call_restart {
flags |= SA_RESTART;
}
flags
}
}
/// The error produced when setting a signal handler fails.
#[derive(Debug)]
#[cfg_attr(all(unix, feature = "signals"), derive(Error))]
pub enum SetHandlerError {
/// An unsafe signal was attempted to be handled using `set` instead of `set_unsafe`.
#[cfg_attr(
all(unix, feature = "signals"),
error("an unsafe signal was attempted to be handled using `set` instead of `set_unsafe`")
)]
UnsafeSignal,
/// The signal which was attempted to be handled is not allowed to be handled by the POSIX specification. This can either be [`ForceSuspend`] or [`Kill`].
///
/// [`Kill`]: enum.SignalType.html#variant.Kill " "
/// [`ForceSuspend`]: enum.SignalType.html#variant.ForceSuspend " "
#[cfg_attr(
all(unix, feature = "signals"),
error("the signal {:?} cannot be handled", .0),
)]
UnblockableSignal(SignalType),
/// The specified real-time signal is not available on this OS.
#[cfg_attr(
all(unix, feature = "signals"),
error(
"the real-time signal number {} is not available ({} is the highest possible)",
.attempted,
.max,
),
)]
RealTimeSignalOutOfBounds {
/// The realtime signal which was attempted to be used.
attempted: u32,
/// The highest available realtime signal number.
max: u32,
},
/// An unexpected OS error ocurred during signal handler setup.
#[cfg_attr(
all(unix, feature = "signals"),
error("{}", .0),
)]
UnexpectedSystemCallFailure(#[cfg_attr(all(unix, feature = "signals"), from)] io::Error),
}
/// The actual hook which is passed to `sigaction` which dispatches signals according to the global handler map (the `HANDLERS` static).
extern "C" fn signal_receiver(signum: i32) {
let catched = panic::catch_unwind(|| {
let handler_and_flags = {
let handlers = HANDLERS.read();
let val = handlers
.get(signum as u64)
.expect("unregistered signal passed by the OS to the shared receiver");
*val
};
match handler_and_flags.0 {
SignalHandler::Ignore => {}
SignalHandler::Hook(hook) => hook.inner()(),
SignalHandler::Default => unreachable!(
"signal receiver was unregistered but has been called by the OS anyway"
),
}
if handler_and_flags.1 & SA_RESETHAND != 0 {
// If the signal is set to be reset to default handling, set the record accordingly.
let mut handlers = HANDLERS.write();
handlers.remove(signum as u64);
let handler_and_flags = (SignalHandler::Default, handler_and_flags.1);
handlers.insert(signum as u64, handler_and_flags);
}
});
// The panic hook already ran, so we only have to abort the process
catched.unwrap_or_else(|_| process::abort());
}
/// A signal handling method.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum SignalHandler {
/// Use the default behavior specified by POSIX.
Default,
/// Ignore the signal whenever it is received.
Ignore,
/// Call a function whenever the signal is received.
Hook(SignalHook),
}
impl SignalHandler {
/// Returns `true` for the [`Default`] variant, `false` otherwise.
///
/// [`Default`]: #variant.Default.html " "
pub const fn is_default(self) -> bool {
matches!(self, Self::Default)
}
/// Returns `true` for the [`Ignore`] variant, `false` otherwise.
///
/// [`Ignore`]: #variant.Ignore.html " "
pub const fn is_ignore(self) -> bool {
matches!(self, Self::Ignore)
}
/// Returns `true` for the [`Hook`] variant, `false` otherwise.
///
/// [`Hook`]: #variant.Hook.html " "
pub const fn is_hook(self) -> bool {
matches!(self, Self::Hook(..))
}
/// Creates a handler which calls the specified function.
///
/// # Safety
/// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
///
/// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
pub unsafe fn from_fn(function: fn()) -> Self {
Self::Hook(unsafe { SignalHook::from_fn(function) })
}
}
impl Default for SignalHandler {
/// Returns [`SignalHandler::Default`].
///
/// [`SignalHandler::Default`]: #variant.Default " "
fn default() -> Self {
Self::Default
}
}
impl From<SignalHook> for SignalHandler {
fn from(op: SignalHook) -> Self {
Self::Hook(op)
}
}
/// A function which can be used as a signal handler.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SignalHook(fn());
impl SignalHook {
/// Creates a hook which calls the specified function.
///
/// # Safety
/// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
///
/// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
pub unsafe fn from_fn(function: fn()) -> Self {
Self(function)
}
/// Returns the wrapped function.
pub fn inner(self) -> fn() {
self.0
}
}
impl From<SignalHook> for fn() {
fn from(op: SignalHook) -> Self {
op.0
}
}
/// Sends the specified signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a Termination signal to the calling process.
/// signal::send(SignalType::Termination, process::id())?;
/// # }
/// # Ok(()) }
/// ```
pub fn send(signal: impl Into<Option<SignalType>>, pid: impl Into<u32>) -> io::Result<()> {
let pid = pid
.to::<u32>()
.try_to::<i32>()
.unwrap_or_else(|_| panic!("process identifier out of range"));
debug_assert_ne!(
pid, 0,
"to send the signal to the process group of the calling process, use send_to_group instead"
);
let success = unsafe { libc::kill(signal.into().map_or(0, Into::into), pid) != -1 };
if success {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// Sends the specified real-time signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a real-timne signal 0 to the calling process.
/// signal::send_rt(0, process::id())?;
/// # }
/// # Ok(()) }
/// ```
pub fn send_rt(signal: impl Into<Option<u32>>, pid: impl Into<u32>) -> io::Result<()> {
let pid = pid
.to::<u32>()
.try_to::<i32>()
.unwrap_or_else(|_| panic!("process identifier out of range"));
debug_assert_ne!(
pid, 0,
"to send the signal to the process group of the calling process, use send_to_group instead"
);
let signal = signal.into().map_or(0, |val| {
assert!(is_valid_rtsignal(val), "invalid real-time signal");
val
}) as i32;
let success = unsafe { libc::kill(signal, pid) != -1 };
if success {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// Sends the specified signal to the specified process group. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a Termination signal to the process group of the calling process.
/// signal::send_to_group(SignalType::Termination, 0_u32)?;
/// # }
/// # Ok(()) }
/// ```
pub fn send_to_group(signal: impl Into<Option<SignalType>>, pid: impl Into<u32>) -> io::Result<()> {
#[allow(clippy::neg_multiply)] // "it's more readable to just negate"? how about no
let pid = pid
.to::<u32>()
.try_to::<i32>()
.unwrap_or_else(|_| panic!("process group identifier out of range"))
* -1;
let success = unsafe { libc::kill(signal.into().map_or(0, Into::into), pid) != -1 };
if success {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// Sends the specified real-time signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(all(unix, feature = "signals"))] {
/// use interprocess::os::unix::signal::{self, SignalType};
/// use std::process;
///
/// // Send a real-timne signal 0 to the process group of the calling process.
/// signal::send_rt(0_u32, 0_u32)?;
/// # }
/// # Ok(()) }
/// ```
pub fn send_rt_to_group(signal: impl Into<Option<u32>>, pid: impl Into<u32>) -> io::Result<()> {
#[allow(clippy::neg_multiply)]
let pid = pid
.to::<u32>()
.try_to::<i32>()
.unwrap_or_else(|_| panic!("process identifier out of range"))
* -1;
debug_assert_ne!(
pid, 0,
"to send the signal to the process group of the calling process, use send_to_group instead"
);
let signal = signal.into().map_or(0, |val| {
assert!(is_valid_rtsignal(val), "invalid real-time signal");
val
}) as i32;
let success = unsafe { libc::kill(signal, pid) != -1 };
if success {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// All standard signal types as defined in POSIX.1-2001.
///
/// The values can be safely and quickly converted to [`i32`]/[`u32`]. The reverse process involves safety checks, making sure that unknown signal values are never stored.
///
/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[repr(i32)]
#[non_exhaustive]
pub enum SignalType {
/// `SIGHUP` – lost connection to controlling terminal. Opting out of this signal is recommended if the process does not need to stop after the user who started it logs out.
///
/// *Default handler: process termination.*
#[cfg(any(doc, se_basic))]
Hangup = SIGHUP,
/// `SIGINT` – keyboard interrupt, usually sent by pressing `Ctrl`+`C` by the terminal. This signal is typically set to be ignored if the program runs an interactive interface: GUI/TUI, interactive shell (the Python shell, for example) or any other kind of interface which runs in a loop, as opposed to a command-line invocation of the program which reads its standard input or command-line arguments, performs a task and exits. If the interactive interface is running a lengthy operation, a good idea is to temporarily re-enable the signal and abort the lengthy operation if the signal is received, then disable it again.
///
/// *Default handler: process termination.*
#[cfg(any(doc, se_basic))]
KeyboardInterrupt = SIGINT,
/// `SIGQUIT` – request to perform a core dump and quit, usually sent by pressing `Ctrl`+`\`. This signal normally should not be overriden or masked out – the core dump is performed automatically by the OS.
///
/// *Default handler: process termination with a core dump.*
#[cfg(any(doc, se_basic))]
QuitAndDump = SIGQUIT,
/// `SIGILL` – illegal or malformed instruction exception, generated by the CPU whenever such an instruction is executed. This signal normally should not be overriden or masked out, since it likely means that the executable file or the memory of the process has been corrupted and further execution is a risk of invoking negative consequences.
///
/// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
///
/// *Default handler: process termination with a core dump.*
#[cfg(any(doc, se_basic))]
IllegalInstruction = SIGILL,
/// `SIGABRT` – abnormal termination requested. This signal is typically invoked by the program itself, using [`std::process::abort`] or the equivalent C function; still, like any other signal, it can be sent from outside the process.
///
/// *Default handler: process termination with a core dump.*
///
/// [`std::process::abort`]: https://doc.rust-lang.org/std/process/fn.abort.html " "
#[cfg(any(doc, se_basic))]
Abort = SIGABRT,
/// `SIGFPE` – mathematical exception. This signal is generated whenever an undefined mathematical operation is performed – mainly integer division by zero.
///
/// *Default handler: process termination with a core dump.*
#[cfg(any(doc, se_basic))]
MathException = SIGFPE,
/// `SIGKILL` – forced termination. This signal can only be sent using the usual signal sending procedures and, unlike most other signals, cannot be masked out or handled at all. The main purpose for this signal is to stop a program which has masked out all other signals for malicious purposes or has stuck in such a state because of a bug.
///
/// *Default handler: process termination, **cannot be overriden or disabled**.*
#[cfg(any(doc, se_basic))]
Kill = SIGKILL,
/// `SIGSEGV` – invaid memory access. This signal is issued by the OS whenever the program tries to access an invalid memory location, such as the `NULL` pointer or simply an address outside the user-mode address space as established by the OS. The only case when this signal can be received by a Rust program is if memory unsafety occurs due to misuse of unsafe code. As such, it should normally not be masked out or handled, as it likely indicates a critical bug (soundness hole), executable file corruption or process memory corruption.
///
/// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
///
/// *Default handler: process termination with a core dump.*
#[cfg(any(doc, se_basic))]
SegmentationFault = SIGSEGV,
/// `SIGPIPE` – invalid access to an [unnamed pipe]. This signal is issued by the OS whenever a program attempts to write to an unnamed pipe which has no readers connected to it. If unexpected, this might mean abnormal termination of the process which the pipe was used to communicate with.
///
/// *Default handler: process termination.*
///
/// [unnamed pipe]: ../../../unnamed_pipe/index.html " "
#[cfg(any(doc, se_basic))]
BrokenPipe = SIGPIPE,
/// `SIGALRM` – "alarm clock" signal. This signal is issued by the OS when the arranged amount of real (wall clock) time expires. This clock can be set using the [`alarm`] and [`setitimer`] system calls.
///
/// *Default handler: process termination.*
///
/// [`alarm`]: https://www.man7.org/linux/man-pages/man2/alarm.2.html " "
/// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
#[cfg(any(doc, se_basic))]
AlarmClock = SIGALRM,
/// `SIGTERM` – request for termination. This signal can only be sent using the usual signal sending procedures. Unlike [`KeyboardInterrupt`], this signal is not a request to break out of a lengthy operation, but rather to close the program as a whole. Signal handlers for this signal are expected to perform minimal cleanup and quick state save procedures and then exit.
///
/// *Default handler: process termination.*
///
/// [`KeyboardInterrupt`]: #variant.KeyboardInterrupt " "
#[cfg(any(doc, se_basic))]
Termination = SIGTERM,
/// `SIGUSR1` – user-defined signal 1. This signal, like [`UserSignal2`], does not have a predefined meaning and is not produced by the OS. For this reason, it is typically used for interprocess communication between two programs familiar with each other, or in language runtimes to signal certain events, such as externally activated immediate garbage collection.
///
/// *Default handler: process termination.*
///
/// [`UserSignal2`]: #variant.UserSignal2 " "
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
UserSignal1 = SIGUSR1,
/// `SIGUSR2` – user-defined signal 2. This signal is similar to [`UserSignal1`] and has the same properties, but is a distinct signal nonetheless.
///
/// *Default handler: process termination.*
///
/// [`UserSignal1`]: #variant.UserSignal1 " "
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
UserSignal2 = SIGUSR2,
/// `SIGCHLD` – child process suspended, resumed or terminated. This signal is issued by the OS whenever a child process is suspended/resumed or terminated by a signal or otherwise.
///
/// *Default handler: ignore.*
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
ChildProcessEvent = SIGCHLD,
/// `SIGCONT` – resume the process after being suspended. This signal can be sent to a process by an external program when it wishes to resume that process after it being suspended in a stopped state.
///
/// *Default handler: continue execution.*
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
Continue = SIGCONT,
/// `SIGSTOP` – forcefully stop a process temporarily. This signal can only be sent to a process by an external program. Unlike [`Suspend`], this signal cannot be masked out or handled, i.e. it is guaranteed to be able to temporarily stop a process from executing without [forcefully terminating it]. The process can then be restarted using [`Continue`].
///
/// *Default handler: temporarily stop process, **cannot be overriden or disabled**.*
///
/// [`Suspend`]: #variant.Suspend " "
/// [forcefully terminating it]: #variant.Kill " "
/// [`Continue`]: #variant.Continue " "
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
ForceSuspend = SIGSTOP,
/// `SIGTSTP` – temporarily stop a process. This signal can only be sent to a process by an external program. Unlike [`ForceSuspend`], this signal can be masked out or handled by the process which is requested to stop. The process can then be restarted using [`Continue`].
///
/// *Default handler: temporarily stop process.*
///
/// [`ForceSuspend`]: #variant.ForceSuspend " "
/// [`Continue`]: #variant.Continue " "
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
Suspend = SIGTSTP,
/// `SIGTTIN` – attempt to read from standard input while in the background. This signal is issued by the OS whenever a process which is under [job control] tries to read from standard input but is in the background, i.e. temporarily detached from the terminal.
///
/// *Default handler: temporarily stop process.*
///
/// [job control]: https://en.wikipedia.org/wiki/Job_control_(Unix) " "
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
TerminalInputWhileInBackground = SIGTTIN,
/// `SIGTTOU` – attempt to write to standard output while in the background. This signal is issued by the OS whenever a process which is under [job control] tries to write to standard input but is in the background, i.e. temporarily detached from the terminal.
///
/// *Default handler: temporarily stop process.*
///
/// [job control]: https://en.wikipedia.org/wiki/Job_control_(Unix) " "
#[cfg(any(doc, se_full_posix_1990))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
TerminalOutputWhileInBackground = SIGTTOU,
/// `SIGPOLL` – watched file descriptor event. This signal is issued by the OS when a file descriptor which has been enabled to interact with this signal has a state update.
///
/// *Default handler: process termination.*
// TODO more on this
#[cfg(any(se_sigpoll, se_sigpoll_is_sigio))]
#[cfg_attr( // any(se_sigpoll, se_sigpoll_is_sigio) template
feature = "doc_cfg",
doc(cfg(any(
target_os = "linux",
target_os = "android",
target_os = "emscripten",
target_os = "redox",
target_os = "haiku",
target_os = "solaris",
target_os = "illumos"
)))
)]
PollNotification = SIGPOLL,
/// `SIGBUS` – [bus error]. This signal is issued by the OS when a process does one of the following:
/// - **Tries to access an invalid physical address**. Normally, this should never happen – attempts to access invalid *virtual* memory are handled as [segmentation faults], and invalid phyiscal addresses are typically not present in the address space of a program in user-mode.
/// - **Performs an incorrectly aligned memory access**. In Rust, this can only happen if unsafe code is misused to construct an incorrectly aligned pointer to a type which requires alignment which is more strict than simple one byte alignment. This is a direct sign of memory unsafety being invoked.
/// - **Incorrect x86 segment register**. This can only be acheieved using inline assembly or FFI (calling an external function written in assembly language or with usage of C/C++ inline assembly), and only on the x86 architecture. If an invalid value is loaded into the segment registers, the CPU generates this exception. This is either a sign of a failed advanced unsafe operation or a deliberate attempt to cryptically crash the program.
///
/// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
///
/// *Default handler: process termination with a core dump.*
///
/// [bus error]: https://en.wikipedia.org/wiki/Bus_error " "
/// [segmentation faults]: #variant.SegmentationFault " "
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
MemoryBusError = SIGBUS,
/// `SIGPROF` – profiler clock signal. This signal is issued by the OS when the arranged amount of CPU time expires. The time includes not only user-mode CPU time spent in the process, but also kernel-mode CPU time which the OS associates with the process. This is different from [`UserModeProfilerClock`]'s behavior, which counts only user-mode CPU time. This clock can be set using the [`setitimer`] system call.
///
/// *Default handler: process termination.*
///
/// [`UserModeProfilerClock`]: #variant.UserModeProfilerClock " "
/// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
ProfilerClock = SIGPROF,
/// `SIGVTALRM` – user-mode profiler clock signal. This signal is issued by the OS when the arranged amount of CPU time expires. Only user-mode CPU time is counted, in contrast to `ProfilerClock`, which counts kernel-mode time associated by the system with the process as well. This clock can be set using the [`setitimer`] system call.
///
/// *Default handler: process termination.*
///
/// [`ProfilerClock`]: #variant.ProfilerClock " "
/// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
UserModeProfilerClock = SIGVTALRM,
/// `SIGSYS` – attempt to perform an invalid system call. This signal is issued by the OS when a system call receives invalid arguments. Normally, the C library functions used to perform system calls in Rust programs do not generate this signal – the only way to generate it is to send it to a process explicitly, use raw system call instructions or violate [`seccomp`] rules if it is enabled.
///
/// *Default handler: process termination with a core dump.*
///
/// [`seccomp`]: https://en.wikipedia.org/wiki/Seccomp " "
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
InvalidSystemCall = SIGSYS,
/// `SIGTRAP` – software breakpoint. This signal is issued by the OS when a breakpoint instruction is executed. On x86, the instruction to do so is `int 3`. This instruction is typically inserted by debuggers and code injection utilities.
///
/// *Default handler: process termination with a core dump.*
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
Breakpoint = SIGTRAP,
/// `SIGURG` – [out-of-band data] received on a socket. This signal is issued by the OS when a socket owned by the process receives urgent out-of-band data.
///
/// *Default handler: ignore.*
///
/// [out-of-band data]: https://en.wikipedia.org/wiki/Out-of-band_data " "
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
OutOfBandDataAvailable = SIGURG,
/// `SIGXCPU` – assigned CPU time limit for the process was exceeded. This signal is issued by the OS if a CPU time limit for the process was set, when that limit expires. If not handled quickly, the system will issue a [`Kill`] signal to shut down the process forcefully, i.e. ignoring this signal won't lead to bypassing the limit. The [`setrlimit`] system call is used to set the soft limit for this signal and the hard limit, which invokes [`Kill`].
///
/// *Default handler: process termination with a core dump.*
///
/// [`setrlimit`]: https://www.man7.org/linux/man-pages/man2/setrlimit.2.html " "
/// [`Kill`]: #variant.Kill " "
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
CpuTimeLimitExceeded = SIGXCPU,
/// `SIGXFSZ` – assigned file size limit for the process was exceeded. This signal is issued by the OS if a limit on the size of files which are written to by the process was set, when that limit is exceeded by the process. If ignored/handled, the offending system call fails with an error regardless of the handling method. The [`setrlimit`] system call is used to set the limit.
///
/// *Default handler: process termination with a core dump.*
///
/// [`setrlimit`]: https://www.man7.org/linux/man-pages/man2/setrlimit.2.html " "
#[cfg(any(doc, se_base_posix_2001))]
#[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
feature = "doc_cfg",
doc(cfg(not(target_os = "hermit"))),
)]
FileSizeLimitExceeded = SIGXFSZ,
}
impl SignalType {
/// Returns `true` if the value is a special signal which cannot be blocked or handled ([`Kill`] or [`ForceSuspend`]), `false` otherwise.
///
/// [`Kill`]: #variant.Kill " "
/// [`ForceSuspend`]: #variant.ForceSuspend " "
pub const fn is_unblockable(self) -> bool {
matches!(self, Self::Kill | Self::ForceSuspend)
}
/// Returns `true` if the value is an unsafe signal which requires unsafe code when setting a handling method, `false` otherwise.
pub const fn is_unsafe(self) -> bool {
matches!(
self,
Self::SegmentationFault | Self::MemoryBusError | Self::IllegalInstruction
)
}
}
impl From<SignalType> for i32 {
fn from(op: SignalType) -> Self {
op as i32
}
}
impl From<SignalType> for u32 {
fn from(op: SignalType) -> Self {
op as u32
}
}
impl TryFrom<i32> for SignalType {
type Error = UnknownSignalError;
#[rustfmt::skip]
fn try_from(value: i32) -> Result<Self, Self::Error> {
match value {
#[cfg(se_basic)] SIGHUP => Ok(Self::Hangup),
#[cfg(se_basic)] SIGINT => Ok(Self::KeyboardInterrupt),
#[cfg(se_basic)] SIGQUIT => Ok(Self::QuitAndDump),
#[cfg(se_basic)] SIGILL => Ok(Self::IllegalInstruction),
#[cfg(se_basic)] SIGABRT => Ok(Self::Abort),
#[cfg(se_basic)] SIGFPE => Ok(Self::MathException),
#[cfg(se_basic)] SIGKILL => Ok(Self::Kill),
#[cfg(se_basic)] SIGSEGV => Ok(Self::SegmentationFault),
#[cfg(se_basic)] SIGPIPE => Ok(Self::BrokenPipe),
#[cfg(se_basic)] SIGALRM => Ok(Self::AlarmClock),
#[cfg(se_basic)] SIGTERM => Ok(Self::Termination),
#[cfg(se_full_posix_1990)] SIGUSR1 => Ok(Self::UserSignal1),
#[cfg(se_full_posix_1990)] SIGUSR2 => Ok(Self::UserSignal2),
#[cfg(se_full_posix_1990)] SIGCHLD => Ok(Self::ChildProcessEvent),
#[cfg(se_full_posix_1990)] SIGCONT => Ok(Self::Continue),
#[cfg(se_full_posix_1990)] SIGSTOP => Ok(Self::ForceSuspend),
#[cfg(se_full_posix_1990)] SIGTSTP => Ok(Self::Suspend),
#[cfg(se_full_posix_1990)] SIGTTIN => Ok(Self::TerminalInputWhileInBackground),
#[cfg(se_full_posix_1990)] SIGTTOU => Ok(Self::TerminalOutputWhileInBackground),
#[cfg(any(se_sigpoll, se_sigpoll_is_sigio))] SIGPOLL => Ok(Self::PollNotification),
#[cfg(se_full_posix_2001)] SIGBUS => Ok(Self::MemoryBusError),
#[cfg(se_full_posix_2001)] SIGPROF => Ok(Self::ProfilerClock),
#[cfg(se_base_posix_2001)] SIGSYS => Ok(Self::InvalidSystemCall),
#[cfg(se_base_posix_2001)] SIGTRAP => Ok(Self::Breakpoint),
#[cfg(se_base_posix_2001)] SIGURG => Ok(Self::OutOfBandDataAvailable),
#[cfg(se_base_posix_2001)] SIGVTALRM => Ok(Self::UserModeProfilerClock),
#[cfg(se_base_posix_2001)] SIGXCPU => Ok(Self::CpuTimeLimitExceeded),
#[cfg(se_base_posix_2001)] SIGXFSZ => Ok(Self::FileSizeLimitExceeded),
_ => Err(UnknownSignalError { value }),
}
}
}
impl TryFrom<u32> for SignalType {
type Error = UnknownSignalError;
fn try_from(value: u32) -> Result<Self, Self::Error> {
value.try_into()
}
}
/// Error type returned when a conversion from [`i32`]/[`u32`] to [`SignalType`] fails.
///
/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
/// [`SignalType`]: enum.SignalType.html " "
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct UnknownSignalError {
/// The unknown signal value which was encountered.
pub value: i32,
}
impl Display for UnknownSignalError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "unknown signal value {}", self.value)
}
}
impl fmt::Binary for UnknownSignalError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "unknown signal value {:b}", self.value)
}
}
impl fmt::LowerHex for UnknownSignalError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "unknown signal value {:x}", self.value)
}
}
impl fmt::UpperExp for UnknownSignalError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "unknown signal value {:X}", self.value)
}
}
impl fmt::Octal for UnknownSignalError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "unknown signal value {:o}", self.value)
}
}
impl Error for UnknownSignalError {}