diff --git a/library/core/src/process.rs b/library/core/src/process.rs index 2f116992e6d91..0cfd163abfaae 100644 --- a/library/core/src/process.rs +++ b/library/core/src/process.rs @@ -3,7 +3,7 @@ //! Most process-related functionality requires std, but [`crash`] is available //! on all targets. -/// Terminates the process in a violent fashion. +/// Terminates the process in a violent but safe fashion. /// /// The function will never return and will immediately terminate the current /// process in a platform specific "abnormal" manner. As a consequence, @@ -15,8 +15,14 @@ /// to match C `abort()` or otherwise perform a "clean" abort. Instead, it emits /// code that will crash the process with as little overhead as possible, such /// as a "halt and catch fire" style instruction. You should generally prefer -/// using `abort` instead except where the absolute minimum overhead is -/// required. +/// using `abort` or one of the other options mentioned in [Exiting the current +/// process], unless absolute minimum overhead is required. +/// +/// While this function provides an abrupt exit, note that it is still a safe +/// form of crashing—unlike, for example, a segfault caused by a null pointer +/// dereference. +/// +/// [Exiting the current process]: ../../std/process/index.html#exiting-the-current-process /// /// # Platform-specific behavior /// diff --git a/library/std/src/process.rs b/library/std/src/process.rs index cc7fab7aba9d1..c72c62e96ea2f 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -36,7 +36,7 @@ //! successfully spawned, any error that happens afterwards will be reported through //! its [`ExitStatus`]. //! -//! # Handling I/O +//! ## Handling I/O //! //! The [`stdout`], [`stdin`], and [`stderr`] of a child process can be //! configured by passing an [`Stdio`] to the corresponding method on @@ -100,7 +100,7 @@ //! assert_eq!(b"test", output.stdout.as_slice()); //! ``` //! -//! # Windows argument splitting +//! ## Windows argument splitting //! //! On Unix systems arguments are passed to a new process as an array of strings, //! but on Windows arguments are passed as a single commandline string and it is @@ -141,6 +141,42 @@ //! Also note that running batch scripts in this way may be removed in the //! future and so should not be relied upon. //! +//! # Exiting the current process +//! +//! Rust provides a few different ways to terminate the currently running program: +//! +//! | API | Unix exit code | Windows exit code | Unix signal | Cleans up resources | +//! |-----------------------------------------------|----------------|----------------------------------------------------|-----------------------------------------------|---------------------| +//! | Return [`ExitCode`] or a `Result` from `main` | User-provided | User-provided | None | Yes | +//! | [`panic!`] | 101 | 101 | None | Yes | +//! | [`exit`] | User-provided | User-provided | None | Partial | +//! | [`abort`] | None | `STATUS_STACK_BUFFER_OVERRUN`[^win-status-overrun] | `SIGABRT` | No | +//! | [`crash`] | None | Unspecified | Unspecified (typically `SIGTRAP` or `SIGILL`) | No | +//! +//! Use these guidelines to pick which to use: +//! +//! * Use `exit` or return `ExitCode` for exiting as part of normal program +//! behavior. These exit with no additional message, just the provided code. +//! * Use `panic!` for unexpected exits, such as bug conditions. This will print a +//! message with the code location and give the option of printing a backtrace. +//! * Prefer versions that clean up resources where possible (return `ExitCode` +//! rather than call `exit`), since these flush buffers and run destructors. +//! * Use `abort` for cases where cleanup must not run. +//! * Use `crash` only when it is critical to terminate with minimal overhead. +//! +//! A few things to note: +//! +//! * `panic!` can be caught be default, other options cannot. +//! * The behavior of `panic!` can be changed via the `-Cpanic` compiler flag. +//! Refer to +//! for details. +//! * Where specified, exact exit codes are subject to change. +//! +//! For further details, refer to the documentation for each API. +//! +//! [^win-status-overrun]: `STATUS_STACK_BUFFER_OVERRUN` is the exit status used +//! by [`__fastfail()`]. It does not mean there is an actual buffer overrun. +//! //! [`spawn`]: Command::spawn //! [`output`]: Command::output //! @@ -156,6 +192,7 @@ //! [`raw_arg`]: crate::os::windows::process::CommandExt::raw_arg //! //! [`CreateProcessW`]: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw +//! [`__fastfail()`]: https://learn.microsoft.com/en-us/cpp/intrinsics/fastfail?view=msvc-170 #![stable(feature = "process", since = "1.0.0")] #![deny(unsafe_op_in_unsafe_fn)] @@ -2597,14 +2634,17 @@ pub fn exit(code: i32) -> ! { /// crate's Cargo.toml, [`panic!`] and `abort` are similar. However, /// [`panic!`] will still call the [panic hook] while `abort` will not. /// -/// If a clean shutdown is needed it is recommended to only call -/// this function at a known point where there are no more destructors left -/// to run. +/// If a clean shutdown is needed it is recommended to only call this function +/// at a known point where there are no more destructors left to run. If an +/// abrupt exit is not needed, one of the other forms of exiting discussed at +/// [Exiting the current process] is likely preferable. /// /// The process's termination will be similar to that from the C `abort()` /// function. On Unix, the process will terminate with signal `SIGABRT`, which /// typically means that the shell prints "Aborted". /// +/// [Exiting the current process]: self#exiting-the-current-process +/// /// # Examples /// /// ```no_run diff --git a/tests/run-make/abort-behavior/rmake.rs b/tests/run-make/abort-behavior/rmake.rs deleted file mode 100644 index 7cef4f347dad4..0000000000000 --- a/tests/run-make/abort-behavior/rmake.rs +++ /dev/null @@ -1,63 +0,0 @@ -//! Check that abort library functions raise the expected signals. - -//@ ignore-cross-compile - -use run_make_support::{bin_name, run_fail_with_args, rustc}; - -#[derive(Debug)] -enum Variant { - Abort, - Crash, -} - -fn main() { - rustc().input("main.rs").run(); - - check_one(Variant::Abort); - check_one(Variant::Crash); -} - -fn check_one(variant: Variant) { - println!("checking variant {variant:?}"); - let arg = match variant { - Variant::Abort => "abort", - Variant::Crash => "crash", - }; - let bin = &bin_name("main"); - let out = run_fail_with_args(bin, &[arg]); - - let status = out.status(); - println!("output status {status}"); - assert!(!status.success()); - - cfg_select! { - unix => { - use std::assert_matches; - use std::os::unix::process::ExitStatusExt; - - use run_make_support::libc; - - let sig = status.signal().expect("no signal recorded"); - match variant { - Variant::Abort => assert_eq!(sig, libc::SIGABRT), - Variant::Crash => assert_matches!(sig, libc::SIGILL | libc::SIGTRAP), - }; - } - windows => { - use run_make_support::windows; - use windows::Win32::Foundation::{ - STATUS_ILLEGAL_INSTRUCTION, STATUS_STACK_BUFFER_OVERRUN, - }; - - let code = status.code().unwrap(); - let expected = match variant { - Variant::Abort => STATUS_STACK_BUFFER_OVERRUN.0, - Variant::Crash => STATUS_ILLEGAL_INSTRUCTION.0, - }; - assert_eq!(code, expected); - } - _ => { - unimplemented!("target may need a new branch") - } - } -} diff --git a/tests/run-make/abort-behavior/main.rs b/tests/run-make/exit-behavior/main.rs similarity index 69% rename from tests/run-make/abort-behavior/main.rs rename to tests/run-make/exit-behavior/main.rs index 01074417fe72f..f0efae397bf88 100644 --- a/tests/run-make/abort-behavior/main.rs +++ b/tests/run-make/exit-behavior/main.rs @@ -5,6 +5,9 @@ fn main() { match arg.as_str() { "abort" => std::process::abort(), "crash" => std::process::crash(), + "panic" => panic!("panic!"), + "exit-0" => std::process::exit(0), + "exit-1" => std::process::exit(1), _ => panic!("unrecognized command {arg}"), } } diff --git a/tests/run-make/exit-behavior/rmake.rs b/tests/run-make/exit-behavior/rmake.rs new file mode 100644 index 0000000000000..e5d51229ebad4 --- /dev/null +++ b/tests/run-make/exit-behavior/rmake.rs @@ -0,0 +1,93 @@ +//! Check exit codes and signals of terminating library functions. + +//@ ignore-cross-compile + +use run_make_support::{bin_name, run_fail_with_args, run_with_args, rustc}; + +#[derive(Debug)] +enum Variant { + Abort, + Crash, + Panic, + Exit0, + Exit1, +} + +fn main() { + rustc().input("main.rs").edition("2024").run(); + + check_one(Variant::Abort); + check_one(Variant::Crash); + check_one(Variant::Panic); + check_one(Variant::Exit0); + check_one(Variant::Exit1); +} + +fn check_one(variant: Variant) { + println!("checking variant {variant:?}"); + let arg = match variant { + Variant::Abort => "abort", + Variant::Crash => "crash", + Variant::Panic => "panic", + Variant::Exit0 => "exit-0", + Variant::Exit1 => "exit-1", + }; + let bin = &bin_name("main"); + + let (out, expected_success) = if matches!(variant, Variant::Exit0) { + (run_with_args(bin, &[arg]), true) + } else { + (run_fail_with_args(bin, &[arg]), false) + }; + + let status = out.status(); + let code = status.code(); + println!("output status for {variant:?}: {status:?}"); + assert_eq!(status.success(), expected_success); + + cfg_select! { + unix => { + use std::assert_matches; + use std::os::unix::process::ExitStatusExt; + + use run_make_support::libc; + + let expected_code = match variant { + Variant::Abort => None, + Variant::Crash => None, + Variant::Panic => Some(101), + Variant::Exit0 => Some(0), + Variant::Exit1 => Some(1), + }; + assert_eq!(code, expected_code); + + let sig = status.signal(); + match variant { + Variant::Abort => assert_eq!(sig, Some(libc::SIGABRT)), + Variant::Crash => assert_matches!(sig, Some(libc::SIGILL | libc::SIGTRAP)), + Variant::Panic => assert_eq!(sig, None), + Variant::Exit0 => assert_eq!(sig, None), + Variant::Exit1 => assert_eq!(sig, None), + }; + } + windows => { + use run_make_support::windows; + use windows::Win32::Foundation::{ + STATUS_ILLEGAL_INSTRUCTION, STATUS_STACK_BUFFER_OVERRUN, + }; + + let code = code.expect("Windows always has an exit code"); + let expected_code = match variant { + Variant::Abort => STATUS_STACK_BUFFER_OVERRUN.0, + Variant::Crash => STATUS_ILLEGAL_INSTRUCTION.0, + Variant::Panic => 101, + Variant::Exit0 => 0, + Variant::Exit1 => 1, + }; + assert_eq!(code, expected_code); + } + _ => { + unimplemented!("target may need a new branch") + } + } +}