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

Clarify Vec::from_raw_parts safety examples #95427

Closed
jmaargh opened this issue Mar 29, 2022 · 1 comment · Fixed by #96222
Closed

Clarify Vec::from_raw_parts safety examples #95427

jmaargh opened this issue Mar 29, 2022 · 1 comment · Fixed by #96222

Comments

@jmaargh
Copy link
Contributor

jmaargh commented Mar 29, 2022

Looking at the documentation for Vec::from_raw_parts it says:

For example it is not safe to build a Vec<u8> from a pointer to a C char array with length size_t.

But it's not clear to me why this is not safe. My guess is that it's assumed to violate the "ptr needs to have been previously allocated via [String]/Vec<T> (at least, it's highly likely to be incorrect if it wasn't)." requirement. However, that's not necessarily the case, consider the following example (which I imagine is one of the main use-cases for this function):

let mut ascii_string_buffer = Vec::<u8>::with_capacity(512);
let ptr = ascii_string_buffer.as_mut_ptr();
let capacity = ascii_string_buffer.capacity();
let mut length = 0;
std::mem::forget(ascii_string_buffer);

unsafe {
    some_ffi_filling_the_buffer(ptr as _, &mut length);
    // error checking...
}

let ascii_string = unsafe { Vec::from_raw_parts(ptr, length, capacity) };

AFAICT this is all safe (assuming the length is checked to be valid after the FFI call). The same region of memory, allocated and deallocated by the correct allocator, with appropriate alignment, and all bit patterns are valid for u8.

Therefore, I suggest modifying the docs to read

For example it is not safe to build a Vec<u8> from an arbitrary pointer to a C char array with length size_t, the array must have been initially allocated by Vec or String for this to be safe.

I haven't checked, but it's possible other from_raw_parts docs could use similar clarifications. I'm happy to make a PR, but wanted to check that I wasn't mistaken first.

@RalfJung
Copy link
Member

Yes that sounds about right. Note that the array must have been specifically allocated with Vec<u8> to make sure the alignment matches. String acts like Vec<u8> in that regard (which we should probably also document).

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