Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check if `panic` is set to `abort` while a library is compiling?

It may be not a good idea or not idiomatic, but let's assume that for some reason a library relies on catch_unwind for its business logic.

Can I somehow warn (by failing the compilation with an error message?) a user of this library if they set panic = "abort" in Cargo.toml of their "terminal" crate?

I was thinking about checking some environment variable in build.rs but can't find any variables with this information.

like image 564
ozkriff Avatar asked Aug 15 '18 14:08

ozkriff


People also ask

How does rust panic work?

The panic! macro signals that your program is in a state it can't handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The Result enum uses Rust's type system to indicate that operations might fail in a way that your code could recover from.

How do you handle panic in Rust?

The behavior of the default std hook, i.e. the code that runs directly after the panic is invoked, is to print the message payload to stderr along with the file/line/column information of the panic!() call. You can override the panic hook using std::panic::set_hook() .


1 Answers

You can use this unstable code in your binary or library to cause an error when -C panic=abort is specified:

#![feature(panic_unwind)]
extern crate panic_unwind;

Which causes this helpful error when the wrong panic strategy is used:

error: the linked panic runtime `panic_unwind` is not compiled with this crate's panic strategy `abort`

When the panic strategy is correct, the extern crate declaration is redundant, but does nothing. When the panic strategy is wrong, it causes a linking error since you can't have two different panic strategy crates in the same binary. Since this check happens when crates are linked, note that if a library is never actually used by the top-level crate, then the check isn't run. (but this is a good thing: if your library is unused, then there is no need for this check anyways!)

Also, this error happens very late in the compilation process, so while cargo build will error out, cargo check won't complain since cargo check doesn't check for linking errors for performance reasons.

Unfortunately, there doesn't seem to be a way to do this on the stable channel.

like image 117
Smitop Avatar answered Oct 09 '22 09:10

Smitop