[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <aBr8rnOk2QmBBR-n@google.com>
Date: Wed, 7 May 2025 06:24:46 +0000
From: Alice Ryhl <aliceryhl@...gle.com>
To: Boqun Feng <boqun.feng@...il.com>
Cc: Andreas Hindborg <a.hindborg@...nel.org>, Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>, Gary Guo <gary@...yguo.net>,
"Björn Roy Baron" <bjorn3_gh@...tonmail.com>, Benno Lossin <benno.lossin@...ton.me>,
Trevor Gross <tmgross@...ch.edu>, Danilo Krummrich <dakr@...nel.org>,
Oliver Mangold <oliver.mangold@...me>, rust-for-linux@...r.kernel.org,
linux-kernel@...r.kernel.org
Subject: Re: [PATCH v2] rust: elaborate safety requirements for `AlwaysReferenceCounted`
On Tue, May 06, 2025 at 07:10:43AM -0700, Boqun Feng wrote:
> On Tue, May 06, 2025 at 10:29:02AM +0200, Andreas Hindborg wrote:
> > Clarify that implementers of `AlwaysReferenceCounted` must prevent the
> > implementer from being directly initialized by users.
> >
> > It is a violation of the safety requirements of `AlwaysReferenceCounted` if
> > its implementers can be initialized on the stack by users. Although this
> > follows from the safety requirements, it is not immediately obvious.
> >
> > The following example demonstrates the issue. Note that the safety
> > requirements for implementing `AlwaysRefCounted` and for calling
> > `ARef::from_raw` are satisfied.
> >
> > struct Empty {}
> >
> > unsafe impl AlwaysRefCounted for Empty {
> > fn inc_ref(&self) {}
> > unsafe fn dec_ref(_obj: NonNull<Self>) {}
> > }
> >
> > fn unsound() -> ARef<Empty> {
> > use core::ptr::NonNull;
> > use kernel::types::{ARef, RefCounted};
> >
> > let mut data = Empty {};
> > let ptr = NonNull::<Empty>::new(&mut data).unwrap();
> > let aref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };
> >
>
> Hmm.. I would say in this case, what gets violated is the safe
> requirement of ARef::from_raw(), because callers are supposed to
> guarantee that an refcount increment was passed to `ARef` and in this
> case, and unsound() cannot guarantee that here because it's going to
> clean up `data` when the it returns.
You can change the example to go through `impl From<&T> for ARef<T>`,
and then you have the same situation without this unsafe op.
Alice
Powered by blists - more mailing lists