Skip to content

Unsound Issue in SpinLock #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
CXWorks opened this issue May 15, 2025 · 2 comments
Closed

Unsound Issue in SpinLock #1

CXWorks opened this issue May 15, 2025 · 2 comments

Comments

@CXWorks
Copy link

CXWorks commented May 15, 2025

Hi, thanks for your time to read this issue.

Our static analyzer find a potential unsound issue (data races) in SpinLock, where the unlock fuction needs to be marked as unsafe explicitly, otherwise safe Rust can have data races when user unlock unexpectedly.

#[inline]
pub fn unlock(&self) {
self.locked.store(false, Ordering::Release);
}

A potentail PoC code is like:

#[deny(unsafe_code)]
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use anode::spinlock::SpinLock;

fn main() {
    let mut s1 = Arc::new(SpinLock::new(5));
    let mut s2 = s1.clone();
    let h = std::thread::spawn(move || {
        let mut guard = s2.lock();
        thread::sleep(Duration::from_secs(1));
        *guard = 10;
        thread::sleep(Duration::from_secs(1));
    });
    thread::sleep(Duration::from_secs(1));
    s1.unlock();
    let guard = s1.lock();
    let origin = *guard;
    for _ in 0..1000000{
        if *guard != origin {
            println!("{} {}", *guard, origin);
            break;
        }

    }
    h.join().unwrap();
}
// output:
// 10 5

Thanks again for your time.

@ekoutanov
Copy link
Member

Only the lock owner should call unlock().

@CXWorks
Copy link
Author

CXWorks commented May 15, 2025

Hi @ekoutanov , thanks for your quick response.

I understand your concern, but Rust is trying to achieve a higher requirement for libraries so that even misuse cannot cause issues, please check this and lock-api for details

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants