Re: C aggregate passing (Rust kernel policy)

Benno Lossin
2025-02-25T22:38:52Z

On 25.02.25 00:04, Ventura Jack wrote:
> On Mon, Feb 24, 2025 at 3:03 PM Benno Lossin <benno.lossin@proton.me> wrote:
>>
>> On 24.02.25 17:57, Ventura Jack wrote:
>>> One example I tested against MIRI:
>>>
>>> use std::cell::UnsafeCell;
>>>
>>> fn main() {
>>>
>>> let val: UnsafeCell<i32> = UnsafeCell::new(42);
>>> let x: & UnsafeCell<i32> = &val;
>>> let y: & UnsafeCell<i32> = &val;
>>>
>>> unsafe {
>>>
>>> // UB.
>>> //let pz: & i32 = & *val.get();
>>>
>>> // UB.
>>> //let pz: &mut i32 = &mut *val.get();
>>>
>>> // Okay.
>>> //let pz: *const i32 = &raw const *val.get();
>>>
>>> // Okay.
>>> let pz: *mut i32 = &raw mut *val.get();
>>>
>>> let px: *mut i32 = x.get();
>>> let py: *mut i32 = y.get();
>>>
>>> *px = 0;
>>> *py += 42;
>>> *px += 24;
>>>
>>> println!("x, y, z: {}, {}, {}", *px, *py, *pz);
>>> }
>>> }
>>>
>>> It makes sense that the Rust "raw pointers" `*const i32` and `*mut
>>> i32` are fine here, and that taking Rust "references" `& i32` and
>>> `&mut i32` causes UB, since Rust "references" have aliasing rules that
>>> must be followed.
>>
>> So it depends on what exactly you do, since if you just uncomment one of
>> the "UB" lines, the variable never gets used and thus no actual UB
>> happens. But if you were to do this:
>
> I did actually test it against MIRI with only one line commented in at
> a time, and the UB lines did give UB according to MIRI, I did not
> explain that.

I do not get UB when I comment out any of the commented lines. Can you
share the output of MIRI?

---
Cheers,
Benno

> It feels a lot like juggling with very sharp knives, but
> I already knew that, because the Rust community generally does a great
> job of warning people against unsafe. MIRI is very good, but it cannot
> catch everything, so it cannot be relied upon in general. And MIRI
> shares some of the advantages and disadvantages of sanitizers for C.
>
> Best, VJ.