Skip to contentSkip to conversation

rust: elaborate safety requirements for `AlwaysReferenceCounted`

PATCH Superseded Andreas Hindborg 2 participants 5 messages May 2, 2025 Rust

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Andreas Hindborg

author reviewer
#0 lore raw

PATCH 1/1 rust: elaborate safety requirements for `AlwaysReferenceCounted`

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) };

      aref

}

---
 rust/kernel/types.rs | 4 ++++
 1 file changed, 4 insertions(+)
rust/kernel/types.rs +4 -0
index 9d0471afc9648f2973235488b441eb109069adb1..193a1356f0df6fede428498485aaef19b4c845c6 100644
@@ -409,6 +409,10 @@ pub const fn raw_get(this: *const Self) -> *mut T {
 /// Implementers must also ensure that all instances are reference-counted. (Otherwise they
 /// won't be able to honour the requirement that [`AlwaysRefCounted::inc_ref`] keep the object
 /// alive.)
+///
+/// Note: This means that implementers must prevent users from directly
+/// initializing the implementer. Otherwise users could initialize the
+/// implementer on the stack, which would violate the safety requirements.
 pub unsafe trait AlwaysRefCounted {
     /// Increments the reference count on the object.
     fn inc_ref(&self);

---
base-commit: b4432656b36e5cc1d50a1f2dc15357543add530e
change-id: 20250502-aref-from-raw-e110b3e6dbf5

Best regards,

Signature · 1 line
Andreas Hindborg <[email protected]>
reviewer
#1 lore raw
Quoted 22 lines · Andreas Hindborg

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};
Quoted 6 lines
      let mut data = Empty {};
      let ptr = NonNull::<Empty>::new(&mut data).unwrap();
      let aref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };

      aref

}

I don't think it's entirely impossible to write an AlwaysRefCounted value that can be on the stack. The type just needs a lifetime parameter. For example, this API is not unsound:

struct MyDataStorage {
    // ...
}
impl MyDataStorage {
    fn as_aref(&self) -> ARef<MyData<'_>> {
        unsafe { ARef::from_raw(ptr::from_ref(self).cast()) }
    }
}

#[repr(transparent)]
struct MyData<'s> {
storage: MyDataStorage,
_lifetime: PhantomData<&'s MyDataStorage>,
}

unsafe impl AlwaysRefCounted for MyData<'_> {
    fn inc_ref(&self) {}
    unsafe fn dec_ref(_obj: NonNull<Self>) {}
}
impl Deref for MyData<'_> {
    type Target = MyDataStorage;
    fn deref(&self) -> &MyDataStorage {
        &self.storage
    }
}

Alice

author reviewer
#2 lore raw
Quoted 55 lines · Alice Ryhl
Quoted 22 lines · Andreas Hindborg

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};
Quoted 6 lines
      let mut data = Empty {};
      let ptr = NonNull::<Empty>::new(&mut data).unwrap();
      let aref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };

      aref

}

I don't think it's entirely impossible to write an AlwaysRefCounted value that can be on the stack. The type just needs a lifetime parameter. For example, this API is not unsound:

struct MyDataStorage {
    // ...
}
impl MyDataStorage {
    fn as_aref(&self) -> ARef<MyData<'_>> {
        unsafe { ARef::from_raw(ptr::from_ref(self).cast()) }
    }
}

#[repr(transparent)]
struct MyData<'s> {
storage: MyDataStorage,
_lifetime: PhantomData<&'s MyDataStorage>,
}

unsafe impl AlwaysRefCounted for MyData<'_> {
    fn inc_ref(&self) {}
    unsafe fn dec_ref(_obj: NonNull<Self>) {}
}
Quoted 6 lines
impl Deref for MyData<'_> {
    type Target = MyDataStorage;
    fn deref(&self) -> &MyDataStorage {
        &self.storage
    }
}

Right. I would rephrase then:

It is a violation of the safety requirements of AlwaysReferenceCounted if its implementers can be initialized on the stack by users and an ARef referencing the object can outlive the object. Although this follows from the safety requirements, it is not immediately obvious.

and

+/// Note: This means that implementers must prevent users from directly +/// initializing the implementer when the implementer is 'static. Otherwise users could +/// initialize the implementer on
+/// the stack, which would violate the safety requirements.

What do you think?

Best regards,
Andreas Hindborg

reviewer
#3 lore raw
Quoted 79 lines · Andreas Hindborg
Quoted 55 lines · Alice Ryhl
Quoted 22 lines · Andreas Hindborg

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};
Quoted 6 lines
      let mut data = Empty {};
      let ptr = NonNull::<Empty>::new(&mut data).unwrap();
      let aref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };

      aref

}

I don't think it's entirely impossible to write an AlwaysRefCounted value that can be on the stack. The type just needs a lifetime parameter. For example, this API is not unsound:

struct MyDataStorage {
    // ...
}
impl MyDataStorage {
    fn as_aref(&self) -> ARef<MyData<'_>> {
        unsafe { ARef::from_raw(ptr::from_ref(self).cast()) }
    }
}

#[repr(transparent)]
struct MyData<'s> {
storage: MyDataStorage,
_lifetime: PhantomData<&'s MyDataStorage>,
}

unsafe impl AlwaysRefCounted for MyData<'_> {
    fn inc_ref(&self) {}
    unsafe fn dec_ref(_obj: NonNull<Self>) {}
}
Quoted 6 lines
impl Deref for MyData<'_> {
    type Target = MyDataStorage;
    fn deref(&self) -> &MyDataStorage {
        &self.storage
    }
}

Right. I would rephrase then:

It is a violation of the safety requirements of AlwaysReferenceCounted if its implementers can be initialized on the stack by users and an ARef referencing the object can outlive the object. Although this follows from the safety requirements, it is not immediately obvious.

and

(quoted diff) +4 -0
+/// Note: This means that implementers must prevent users from directly
+/// initializing the implementer when the implementer is `'static`. Otherwise users could
+/// initialize the implementer on
+/// the stack, which would violate the safety requirements.
Quoted 1 line

What do you think?

Hmm. Perhaps we should say that you can never own it "by value". There must always be pointer indirection.

Alice

author reviewer
#4 lore raw
Quoted 80 lines · Alice Ryhl
Quoted 79 lines · Andreas Hindborg
Quoted 55 lines · Alice Ryhl
Quoted 22 lines · Andreas Hindborg

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};
Quoted 6 lines
      let mut data = Empty {};
      let ptr = NonNull::<Empty>::new(&mut data).unwrap();
      let aref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };

      aref

}

I don't think it's entirely impossible to write an AlwaysRefCounted value that can be on the stack. The type just needs a lifetime parameter. For example, this API is not unsound:

struct MyDataStorage {
    // ...
}
impl MyDataStorage {
    fn as_aref(&self) -> ARef<MyData<'_>> {
        unsafe { ARef::from_raw(ptr::from_ref(self).cast()) }
    }
}

#[repr(transparent)]
struct MyData<'s> {
storage: MyDataStorage,
_lifetime: PhantomData<&'s MyDataStorage>,
}

unsafe impl AlwaysRefCounted for MyData<'_> {
    fn inc_ref(&self) {}
    unsafe fn dec_ref(_obj: NonNull<Self>) {}
}
Quoted 6 lines
impl Deref for MyData<'_> {
    type Target = MyDataStorage;
    fn deref(&self) -> &MyDataStorage {
        &self.storage
    }
}

Right. I would rephrase then:

It is a violation of the safety requirements of AlwaysReferenceCounted if its implementers can be initialized on the stack by users and an ARef referencing the object can outlive the object. Although this follows from the safety requirements, it is not immediately obvious.

and

(quoted diff) +4 -0
+/// Note: This means that implementers must prevent users from directly
+/// initializing the implementer when the implementer is `'static`. Otherwise users could
+/// initialize the implementer on
+/// the stack, which would violate the safety requirements.
Quoted 4 lines
Quoted 1 line

What do you think?

Hmm. Perhaps we should say that you can never own it "by value". There must always be pointer indirection.

Yes, that could work. I'll send a new version.

Best regards,
Andreas Hindborg