I know that Mutex
is an invariant Rust type, so Mutex<&'a T>
cannot be converted to Mutex<&'b T>
even if 'a
outlives 'b
.
In my code I want to convert Arc<Mutex<&'a mut T>>
to Arc<Mutex<&'b mut T>>
to shorten the lifetime of the reference, e.g. smth like this:
fn shorten_mutex_lifetime<'a, 'b, T>(
m: Arc<Mutex<&'a mut T>>
) -> Arc<Mutex<&'b mut T>>
where
'a: 'b,
{
unsafe { transmute(m) }
}
Will this be sound or not?
No, it is not safe.
Imagine this was allowed. Then I could take a Arc<Mutex<&'long_lived mut T>>
and transform it into Arc<Mutex<&'short_lived mut T>>
. Then I lock()
and assign a value that is short-lived. After that, I'll wait until 'short_lived
expires, then read the value from a copy of the original Mutex
(which is 'long_lived
). But the value has been freed - we have a use after free.