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

Rust allows &mut aliasing on static mut variables #47756

Closed
archshift opened this issue Jan 25, 2018 · 4 comments
Closed

Rust allows &mut aliasing on static mut variables #47756

archshift opened this issue Jan 25, 2018 · 4 comments
Labels
A-borrow-checker Area: The borrow checker C-feature-request Category: A feature request, i.e: not implemented / a PR. T-lang Relevant to the language team, which will review and decide on the PR/issue.

Comments

@archshift
Copy link
Contributor

Simple example:

static mut oops: u32 = 0u32;

pub fn main() {
    let a = unsafe { &mut oops };
    let b = unsafe { &mut oops };
    *a = 1;
    println!("{}", *b);
}

I would expect Rust to disallow this type of code, or at least warn about it, but it simply allows the programmer to shoot himself in the foot.

@kennytm kennytm added A-borrow-checker Area: The borrow checker T-lang Relevant to the language team, which will review and decide on the PR/issue. labels Jan 25, 2018
@scottmcm
Copy link
Member

The fact that you can't do this without unsafe is what I'd call warning about it. You could consider the unsafe like "allowing the cannot_prove_this_code_safe lint".

unsafe can easily get you &mut aliasing on non-globals too:

pub fn main() {
    let mut foo = 4;
    let oops = &mut foo as *mut _;
    let a = unsafe { &mut* oops }; // very bad
    let b = unsafe { &mut* oops }; //  much UB
    *a = 1;
    println!("{}", *b);
}

@cuviper
Copy link
Member

cuviper commented Jan 26, 2018

While it may feel like the borrow checker could catch this local case, static mut references could alias from afar too -- from calls in distant parts of the stack, or even from separate threads.

@archshift
Copy link
Contributor Author

Unfortunately, this isn’t even documented in the rust book. There’s a whole section on mutability in statics but no mention of the relaxed checks on them: namely mutable aliasing and the lack of a Sync requirement.

@XAMPPRocky XAMPPRocky added the C-feature-request Category: A feature request, i.e: not implemented / a PR. label Apr 23, 2018
@Centril
Copy link
Contributor

Centril commented Feb 18, 2019

Closing based on #47756 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-borrow-checker Area: The borrow checker C-feature-request Category: A feature request, i.e: not implemented / a PR. T-lang Relevant to the language team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

6 participants