Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the following lifetime shortage conversion sound?

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?

like image 982
Dmitry Gordon Avatar asked Oct 15 '25 16:10

Dmitry Gordon


1 Answers

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.

like image 54
Chayim Friedman Avatar answered Oct 18 '25 11:10

Chayim Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!