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

Region-is-free check is unsound due to a race condition #2

Closed
dtolnay opened this Issue Dec 9, 2018 · 2 comments

Comments

Projects
None yet
2 participants
@dtolnay

dtolnay commented Dec 9, 2018

region_buffer/src/lib.rs

Lines 197 to 199 in 45d6c7b

self.assert_region_is_free(start, end);
self.ranges.write().unwrap().insert((start, end));

This check is not thread safe. RegionBuffer implements Sync so some other thread may have mutably claimed the same region in between those two lines. This is unsound because you would end up having handed out multiple mutable borrows of the same data.

@dtolnay

This comment has been minimized.

dtolnay commented Dec 9, 2018

Here is code to trigger the race condition. If you run this a few times with cargo run you will see it sometimes prints COUNT greater than 1 which indicates unsound simultaneous mutable borrows of the same element.

use region_buffer::region_buffer;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::Duration;

fn main() {
    let rb = Arc::new(RwLock::new(region_buffer![0]));
    let latch = rb.write().unwrap();

    let mut threads = Vec::new();
    for _ in 0..10 {
        let rb = rb.clone();
        threads.push(thread::spawn(move || {
            let rb = rb.read().unwrap();
            rb.get_mut(0)
        }));
    }

    thread::sleep(Duration::from_millis(100));
    drop(latch);

    let mut count = 0;
    for thread in threads {
        if thread.join().is_ok() {
            count += 1;
        }
    }
    println!("COUNT = {}", count);
}

@xfix xfix referenced this issue Dec 9, 2018

Merged

Resolve safety issues #5

@Aaronepower

This comment has been minimized.

Owner

Aaronepower commented Dec 10, 2018

fixed by #5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment