Re: [PATCH v2 1/3] rust: kernel: add ScatterList abstraction

From: Boqun Feng
Date: Wed Jun 07 2023 - 13:20:11 EST


On Tue, Jun 06, 2023 at 03:01:30PM +0800, Qingsong Chen wrote:
> On 6/5/23 11:26 PM, Boqun Feng wrote:
> > On Fri, Jun 02, 2023 at 06:18:17PM +0800, Qingsong Chen wrote:
> > [...]
> > > +impl<'a> ScatterList<'a> {
> > > + /// Construct a new initializer.
> > > + pub fn new(buf: &'a Pin<&mut [u8]>) -> impl PinInit<ScatterList<'a>> {
> > > + // SAFETY: `slot` is valid while the closure is called, the memory
> > > + // buffer is pinned and valid.
> > > + unsafe {
> > > + init::pin_init_from_closure(move |slot: *mut Self| {
> > > + (*slot).set_buf(buf);
> > > + (*slot).mark_end();
> >
> > Benno can provide more information, but you cannot dereference or create
> > a reference to `*slot`, since `slot` points to an uninitialized object
> > (see `try_pin_init` implementations), and referencing uninitialized
> > objects is UB (or may cause UB).
>
> I understand that `reading` from uninitialized objects is UB, either
> via references or raw pointers. But in this unsafe closure, we just do
> the `writing` job to `slot` for initializing. This makes me a little
> confused, why is there a difference between reference and raw pointer?

References (or the existence of the references) mean the underlying
objects are valid:

https://doc.rust-lang.org/std/primitive.reference.html

, so creating a reference (even a temporary one) to an uninitialized is
an UB, that being said..

> Is there any compiler magic on reference which may cause UB? Still, I

I'm not creative enough to come up with a compiler optimization that
will (ab)use this UB to do evil if you can be sure that set_buf() and
mark_end() are purely writes. So your confusion looks reasonable to me
;-) But still it's an UB. And I guess you don't want to be suprised by
any future compiler optimization, right? ;-)

Regards,
Boqun

> would fix this by `addr_of`. Thanks.