Re: [PATCH v2 2/7] rust: cred: add Rust abstraction for `struct cred`

From: Boqun Feng
Date: Sun Dec 10 2023 - 20:21:43 EST


On Wed, Dec 06, 2023 at 11:59:47AM +0000, Alice Ryhl wrote:
[...]
> @@ -151,6 +152,21 @@ pub fn as_ptr(&self) -> *mut bindings::file {
> self.0.get()
> }
>
> + /// Returns the credentials of the task that originally opened the file.
> + pub fn cred(&self) -> &Credential {

I wonder whether it would be helpful if we use explicit lifetime here:

pub fn cred<'file>(&'file self) -> &'file Credential

It might be easier for people to get. For example, the lifetime of the
returned Credential reference is constrainted by 'file, the lifetime of
the file reference.

But yes, maybe need to hear others' feedback first.

Regards,
Boqun

> + // SAFETY: Since the caller holds a reference to the file, it is guaranteed that its
> + // refcount does not hit zero during this function call.
> + //
> + // It's okay to read the `f_cred` field without synchronization as `f_cred` is never
> + // changed after initialization of the file.
> + let ptr = unsafe { (*self.as_ptr()).f_cred };
> +
> + // SAFETY: The signature of this function ensures that the caller will only access the
> + // returned credential while the file is still valid, and the C side ensures that the
> + // credential stays valid at least as long as the file.
> + unsafe { Credential::from_ptr(ptr) }
> + }
> +
> /// Returns the flags associated with the file.
> ///
> /// The flags are a combination of the constants in [`flags`].
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index ce9abceab784..097fe9bb93ed 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -33,6 +33,7 @@
> #[cfg(not(testlib))]
> mod allocator;
> mod build_assert;
> +pub mod cred;
> pub mod error;
> pub mod file;
> pub mod init;
>
> --
> 2.43.0.rc2.451.g8631bc7472-goog
>
>