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

UB with ThinVec::new #24

Closed
Cyborus04 opened this issue Oct 22, 2021 · 4 comments
Closed

UB with ThinVec::new #24

Cyborus04 opened this issue Oct 22, 2021 · 4 comments

Comments

@Cyborus04
Copy link

Cyborus04 commented Oct 22, 2021

The following code is unsound, yet compiles:

use thin_vec::ThinVec;

fn main() {
    // this can be any type, not just `u8`
    let mut vec_a = ThinVec::<u8>::new();
    let mut vec_b = ThinVec::<u8>::new();

    let slice_a = vec_a.as_mut_slice();
    let slice_b = vec_b.as_mut_slice();

    assert!(std::ptr::eq(slice_a, slice_b));
}

This triggers 2 forms of undefined behavior:
1. slice_a and slice_b are aliased mutable references. nevermind, see below
2. slice_a and slice_b are mutable references created from a shared reference. ThinVec::new() turns a &Header into a *mut Header, then ThinVec::as_mut_slice creates a &mut [T] from this pointer

@Cyborus04
Copy link
Author

Cyborus04 commented Oct 22, 2021

Wait, do the aliasing rules apply to ZSTs?
Either way, 2 is still an issue

@Cyborus04
Copy link
Author

Cyborus04 commented Oct 22, 2021

The same example still compiles and doesn't panic if you use Vec, so I assume that's alright

Edit:
Yes, this is okay

Aliasing only occurs when memory regions, within which the objects are stored, overlap. Since the memory regions occupied by ZSTs are, obviously, zero-sized, there can never be any overlap, even for pointers with the same address.

from rust-lang/rust-memory-model#44 (comment)

@Gankra
Copy link
Owner

Gankra commented Oct 22, 2021

PS: if you think something is UB, consider running it under miri. It's not perfect but if miri's happy, that's a pretty good sign you're doing something fine.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=775af409fd3ce3283507d11e9082c380

(See Tools > Miri in the top right)

@Gankra Gankra closed this as completed Oct 22, 2021
@Cyborus04
Copy link
Author

Now I feel silly, sorry about this

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