简体   繁体   English

编写预期存在段错误的Rust测试

[英]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. 我想在Rust中编写一个测试,其中#[test]函数的预期行为是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. 首先,我想指出的是,我所知道的唯一的确定段错误的方法是将SIGSEGV信号发送到您自己的进程,可能使用“ raise”功能或等效的rust。

Dereferencing a pointer to unallocated memory or a null pointer doesn't actually guarantee segfault, though it will on most modern platforms. 取消引用指向未分配内存的指针或空指针实际上并不能保证segfault,尽管在大多数现代平台上都可以。

The simplest way to check for a segfault is to fork your program (possibly using the nix crate ). 检查段错误的最简单方法是派生程序(可能使用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. 不过,我不知道Rust板条箱会执行静态分析,因此我想您将依赖于使用C ABI的extern工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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