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

Maybe unsound in as_bytes #2305

Open
lwz23 opened this issue Dec 5, 2024 · 2 comments
Open

Maybe unsound in as_bytes #2305

lwz23 opened this issue Dec 5, 2024 · 2 comments

Comments

@lwz23
Copy link

lwz23 commented Dec 5, 2024

unsafe { slice::from_raw_parts(self.offset as *const u8, self.length as usize) }

pub fn as_bytes(&self) -> &[u8] {
        unsafe { slice::from_raw_parts(self.offset as *const u8, self.length as usize) }
    }

I'm not sure if this code has an unsound problem, but it calls from_raw_parts without any checks. Although memory is a private mod, I decided to report the issue because I didn't see any //SAFETY to indicate this.

@chipshort
Copy link
Collaborator

I'm pretty sure it's not unsound because the only way we create the Regions is from a Vec or from a slice which both should fulfill all the safety requirements.
But it's always a good idea to document this.

@aumetra
Copy link
Member

aumetra commented Dec 12, 2024

Yeah, the idea here is that from_parts upholds all the safety invariants one might need to uphold for us to construct a slice from raw parts.

This is why it's marked as unsafe. If you don't uphold these invariants, you trigger UB. But that's 100% on you because you violated the safety contract.

Admittedly this is very much underdocumented, but you could only have UB here if you violated the safety contract you agreed to when calling from_parts (similarly to Vec::from_raw_parts). And the functions to construct it from a slice or vec are safe since we take ownership and can uphold the safety contract ourselves.

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

3 participants