paranoia/
lib.rs

1//! Paranoia is a simple hack to see if some code was optimized
2//! away (by never being called) or not. This only serves as a
3//! hint because sometimes the compiler isn't able to determine
4//! whether code is able to be fully eliminated or not. But there
5//! are no false negatives - if `marker_exists` returns false, you
6//! can be certain that the call to marker was fully optimized away.
7//!
8//! # Examples
9//!
10//! `Cargo.toml`
11//!
12//! ```no_build
13//! [dependencies]
14//! paranoia-caller = "*"
15//! paranoia = "*"
16//! ```
17//!
18//! verify that it was optimized out:
19//! ```
20//! if false {
21//!     paranoia_caller::mark();
22//! }
23//! assert!(!paranoia::marker_exists());
24//! ```
25//!
26//! see if it was not able to be optimized out:
27//! ```
28//! if true {
29//!     paranoia_caller::mark();
30//! }
31//! assert!(paranoia::marker_exists());
32//! ```
33
34fn exists() -> bool {
35    use libc::{dlsym, RTLD_NEXT};
36    use std::ffi::CString;
37
38    let symbol = CString::new(b"___paranoia_present".to_vec()).unwrap();
39
40    #[allow(unsafe_code)]
41    let ptr = unsafe { dlsym(RTLD_NEXT, symbol.as_ptr()) };
42
43    !ptr.is_null()
44}
45
46lazy_static::lazy_static! {
47    static ref EXISTS: bool = exists();
48}
49
50/// Check to see if the marker has been optimized away or not.
51pub fn marker_exists() -> bool {
52    *EXISTS
53}