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

From: Qingsong Chen
Date: Tue Jun 06 2023 - 03:01:57 EST


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?
Is there any compiler magic on reference which may cause UB? Still, I
would fix this by `addr_of`. Thanks.