1209: Maybe improve safety of MemoryView Deref r=MarkMcCaskey a=MarkMcCaskey

Possibly slightly better... (effectively does exactly the same thing the same way):

Notably this code still violates the safety rules of its unsafe functions:

It violates rule 2 from https://doc.rust-lang.org/std/slice/fn.from_raw_parts_mut.html :

> The memory referenced by the returned slice must not be accessed through any other pointer (not derived from the return value) for the duration of lifetime ’a. Both read and write accesses are forbidden.


Some comments in the stdlib indicate that casting between `Cell<T>` and `T` isn't something that's safe to do outside of the stdlib 🤷‍♂ .

Fundamentally, `MemoryView` is unsound.  Our docs say that it does not have undefined behavior, but we don't properly justify that.   I believe it relies very heavily on undefined behavior.

Looking for feedback here about what we can do.  It seems like we'll have to break the public API to make a sound API... if we can decide on a sufficiently good one, we can deprecate the old one and roll out the new one to prevent user breakage.

We may need to use something like https://docs.rs/crossbeam/0.7.3/crossbeam/atomic/struct.AtomicCell.html or implement something like it.

Where I'm at in regards to memory access from the host is that it's not possible to make any kind of efficient API that is not entirely `unsafe`.  Even given that, we need to figure out the bounds with which the `unsafe` functions can be used relatively safely.  I think even if we marked our existing functions as `unsafe`, it's too complex to figure out whether or not you're using it correctly...

Bonus points if your solution works across multiple threads properly...

# Review

- [ ] Add a short description of the the change to the CHANGELOG.md file


Co-authored-by: Mark McCaskey <mark@wasmer.io>
Co-authored-by: Mark McCaskey <5770194+MarkMcCaskey@users.noreply.github.com>
This commit is contained in:
bors[bot] 2020-02-14 00:13:48 +00:00 committed by GitHub
commit f4829c7fe5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -82,7 +82,9 @@ impl<'a, T: Atomic> MemoryView<'a, T> {
impl<'a, T> Deref for MemoryView<'a, T, NonAtomically> {
type Target = [Cell<T>];
fn deref(&self) -> &[Cell<T>] {
unsafe { slice::from_raw_parts(self.ptr as *const Cell<T>, self.length) }
let mut_slice: &mut [T] = unsafe { slice::from_raw_parts_mut(self.ptr, self.length) };
let cell_slice: &Cell<[T]> = Cell::from_mut(mut_slice);
cell_slice.as_slice_of_cells()
}
}