Skip to content
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

Lazy can cause UB when initialization fails, and program retries initialization #46

Closed
KamilaBorowska opened this issue Sep 1, 2019 · 1 comment · Fixed by #47
Closed

Comments

@KamilaBorowska
Copy link

KamilaBorowska commented Sep 1, 2019

The following program causes UB:

use once_cell::sync::Lazy;

static HI: Lazy<i32> = Lazy::new(|| {
    panic!();
});

fn main() {
    let _ = std::panic::catch_unwind(|| println!("{}", *HI));
    println!("{}", *HI);
}

This is because of incorrect use of unreachable_unchecked when Lazy structure is poisoned.

        pub fn force(this: &Lazy<T, F>) -> &T {
            // Safe because closure is guaranteed to be called at most once
            // so we only call `F` once, this also guarantees no race conditions
            this.cell.get_or_init(|| unsafe {
                match (*this.init.get()).take() {
                    Some(f) => f(),
                    None => unreachable_unchecked(),
                }
            })
        }

This should panic instead of causing unreachable UB.

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

Successfully merging a pull request may close this issue.

2 participants