Re: [PATCH 13/13] rust: sync: introduce `LockedBy`

From: Benno Lossin
Date: Thu Mar 30 2023 - 17:11:15 EST


On 30.03.23 23:04, Wedson Almeida Filho wrote:
> On Thu, 30 Mar 2023 at 08:45, Benno Lossin <y86-dev@xxxxxxxxxxxxxx> wrote:
>>
>> On 30.03.23 13:28, Benno Lossin wrote:
>> struct Outer {
>> mtx1: Mutex<()>,
>> mtx2: Mutex<()>,
>> inners: Vec<Inner>,
>> }
>>
>> struct Inner {
>> count: LockedBy<usize, ()>,
>> }
>>
>> fn new_inner(outer: &Outer) -> Inner {
>> Inner { count: LockedBy::new(&outer.mtx1, 0) }
>> }
>>
>> fn evil(outer: &Outer) {
>> let inner = outer.inners.get(0).unwrap();
>> let mut guard1 = outer.mtx1.lock();
>> let mut guard2 = outer.mtx2.lock();
>> // The pointee of `guard1` and `guard2` have the same address.
>> let ref1 = inner.count.access_mut(&mut *guard1);
>> let ref2 = inner.count.access_mut(&mut *guard2);
>> mem::swap(ref1, ref2);
>> }
>
> This doesn't reproduce the issue because `mtx2` itself is not a ZST
> (it contains a `struct mutex` before the data it protects).
>
> Something like the following should reproduce it though:
>
> struct Outer {
> mtx1: Mutex<()>,
> zst: (),
> }
>
> fn evil(outer: &Outer) {
> let lb = LockedBy::new(&outer.mtx1, 0u8);
> let value = lb.access(&outer.zst);
> // Accessing "value" without holding `mtx1`.
> pr_info!("{}", *value);
> }

You are correct, but in your example you also cannot be sure that it
works, since the layout of the `Mutex` and `Outer` is `repr(Rust)`.
And so you cannot be sure that `zst` has the same address as `value`
inside of the `Mutex` (since the `struct mutex` could be in between).
But regardless, lets just deny ZSTs in `LockedBy` since the fix is
easy and it would be weird to put a ZST in a lock in the first place.
(Not that you have argued against it)

--
Cheers,
Benno