Open
Description
Is it sound to produce a &[u8]
and a &UnsafeCell
which refer to the same region of memory and are live at the same time so long as no code performs mutation operations via the latter reference?
If this is sound, then it's possible to write a wrapper type which "disables" interior mutability by simply not exposing it, which is useful for caes such as google/zerocopy#5 (specifically, we are running into issues with how to define the MaybeValid
type).
Activity
RalfJung commentedon Aug 29, 2023
This is intended to be sound but Stacked Borrows has issues with it, see #303.
joshlf commentedon Aug 29, 2023
Gotcha. Sounds like the current state of things is that:
Is it the case that, as is mentioned in the issue you linked, replacing
&UnsafeCell
with&MaybeUninit<UnsafeCell>
makes it so that this is guaranteed to be sound? Or, as is speculated in the issue thread, is that just a limitation of Miri being able to see throughMaybeUninit
?RalfJung commentedon Aug 29, 2023
The issue mentions replacing
UnsafeCell<T>
withMaybeUninit<T>
. That is unsound,&MaybeUninit<T>
must be read-only like all shared references. I have no idea what the person in the issue meant when they said usingMaybeUninit
could help; it shouldn't make a difference (and we never got an example of it making a difference, so I think they were just confused and there are other things that changed at the same time).RalfJung commentedon Aug 29, 2023
To add to the list: under Tree Borrows, this is sound.
joshlf commentedon Aug 29, 2023
Ah gotcha. I'm asking a slightly different question, which is: Does stacked borrows consider it insta-UB to have
&[u8]
and&MaybeUninit<UnsafeCell>
live at the same time? In other words, doesMaybeUninit
(or really any similarly-shaped union) serve as the hypothetical "disable interior mutability" type I was referring to in the original comment?Unfortunately, I answered my own question in the negative (that code is adapted from the code in #303).
RalfJung commentedon Aug 29, 2023
UnsafeCell
" property into separateImmutable
trait; allowFromZeros
,FromBytes
, andAsBytes
on types withUnsafeCell
s google/zerocopy#251KnownLayout
trait and custom DSTs google/zerocopy#29UnsafeCell
s google/zerocopy#694UnsafeCell
#495[pointer] Relax UnsafeCell requirements
[pointer] Relax UnsafeCell requirements (#1211)