简体   繁体   中英

Writing a Rust test which expects a segfault

I'd like to write a test in Rust where the expected behaviour of the #[test] function is to segfault. Is this possible?

First, I'd like to point out that the only sure way to segfault that I am aware of is to send the SIGSEGV signal to your own process, possibly using the "raise" function or a rust equivalent.

Dereferencing a pointer to unallocated memory or a null pointer doesn't actually guarantee segfault, though it will on most modern platforms.

The simplest way to check for a segfault is to fork your program (possibly using the nix crate ). Once done, execute the function that should make you segfault on the child process, while the parent process waits.

After waiting a sufficient amount of time (any more than a few hundred milliseconds is overkill), check that the child thread is dead. To do that, simply kill it, and an error should be raised if it's already dead.

The only correct way to test this is, in my opinion, pretty heavy. In the test, I would run a static analyser that can detect this possible undefined behavior, and verify that this very issue is still there.

I am not aware of a Rust crate that does a static analysis, though, so I guess that you would depend on an extern tool using the C ABI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM