Re: C aggregate passing (Rust kernel policy)

Gary Guo
2025-02-24T00:27:58Z

On Sun, 23 Feb 2025 08:30:06 -0700
Ventura Jack <venturajack85@gmail.com> wrote:

> - In unsafe Rust, it is the programmer's responsibility
> to obey the aliasing rules, though the type system
> can offer limited help.
> - The aliasing rules in Rust are possibly as hard or
> harder than for C "restrict", and it is not possible to
> opt out of aliasing in Rust, which is cited by some
> as one of the reasons for unsafe Rust being
> harder than C.

The analogy is correct, you can more or less treat all Rust references
a `restrict` pointers. However it is possible to opt out, and it is
done at a per-type basis.

Rust provides `UnsafeCell` to make a immutable reference mutable (i.e.
"interior mutability"), and this makes `&UnsafeCell<T>` behaves like
`T*` in C.

There's another mechanism (currently under rework, though) that makes a
mutable reference behave like `T*` in C.

RfL provides a `Opaque` type that wraps these mechanisms so it
absolutely cancel out any assumptions that the compiler can make about
a pointer whatsoever. For extra peace of mind, this is used for all
data structure that we share with C.

This type granularity is very useful. It allows selective opt-out for
harder to reason stuff, while it allows the compiler (and programmers!)
to assume that, say, if you're dealing with an immutable sequence of
bytes, then calling an arbitrary function will not magically change
contents of it.

Best,
Gary

> - It is necessary to have some understanding of the
> aliasing rules for Rust in order to work with
> unsafe Rust in general.
> - Many find unsafe Rust harder than C:
> https://chadaustin.me/2024/10/intrusive-linked-list-in-rust/
> https://lucumr.pocoo.org/2022/1/30/unsafe-rust/
> https://youtube.com/watch?v=DG-VLezRkYQ
> Unsafe Rust being harder than C and C++ is a common
> sentiment in the Rust community, possibly the large
> majority view.
> - Some Rust developers, instead of trying to understand
> the aliasing rules, may try to rely on MIRI. MIRI is
> similar to a sanitizer for C, with similar advantages and
> disadvantages. MIRI uses both the stacked borrow
> and the tree borrow experimental research models.
> MIRI, like sanitizers, does not catch everything, though
> MIRI has been used to find undefined behavior/memory
> safety bugs in for instance the Rust standard library.
>
> So if you do not wish to deal with aliasing rules, you
> may need to avoid the pieces of code that contains unsafe
> Rust.
>
> Best, VJ.