[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <87r011pzl2.fsf@kernel.org>
Date: Tue, 06 May 2025 16:45:45 +0200
From: Andreas Hindborg <a.hindborg@...nel.org>
To: "Boqun Feng" <boqun.feng@...il.com>
Cc: "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>,
"Alice Ryhl" <aliceryhl@...gle.com>, "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`
"Boqun Feng" <boqun.feng@...il.com> writes:
> 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.
Right, `unsound` is not following this part of the safety requirement:
and that they are properly relinquishing one increment ...
callers must not use the underlying object anymore
Freeing the object by returning is using the object.
So maybe we don't need to change anything, we can just fix up the
example for `ARef::into_raw`.
Best regards,
Andreas Hindborg
Powered by blists - more mailing lists