Skip to content

Unsound Issue in SpinLock #1

@CXWorks

Description

@CXWorks

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions