Re: [PATCH 04/10] rust: Add bindings for reading device properties

Remo Senekowitsch
2025-04-02T16:28:31Z

On Wed Mar 26, 2025 at 10:27 PM CET, Rob Herring wrote:
> On Wed, Mar 26, 2025 at 06:13:43PM +0100, Remo Senekowitsch wrote:
>> + pub fn property_read_string(&self, name: &CStr) -> Result<CString> {
>> + let mut str = core::ptr::null_mut();
>> + let pstr: *mut _ = &mut str;
>> +
>> + // SAFETY: `name` is non-null and null-terminated. `self.as_raw` is
>> + // valid because `self` is valid.
>> + let ret = unsafe {
>> + bindings::fwnode_property_read_string(self.as_raw(), name.as_char_ptr(), pstr as _)
>> + };
>> + to_result(ret)?;
>> +
>> + // SAFETY: `pstr` contains a non-null ptr on success
>> + let str = unsafe { CStr::from_char_ptr(*pstr) };
>> + Ok(str.try_into()?)
>> + }
>
> There's a problem with the C version of this function that I'd like to
> not repeat in Rust especially since ownership is clear.
>
> The issue is that we never know when the returned string is no longer
> needed. For DT overlays, we need to be able free the string when/if an
> overlay is removed. Though overlays are somewhat orthogonal to this.
> It's really just when the property's node refcount goes to 0 that the
> property value could be freed.
>
> So this function should probably return a copy of the string that the
> caller owns.

I think the function already does that. The variable `str` is of type `&CStr`,
so the expression `str.try_into()?` on the last line calls the implementation
of `impl TryFrom<&CStr> for CString`, which is documented here:
https://rust.docs.kernel.org/kernel/str/struct.CString.html#impl-TryFrom%3C%26CStr%3E-for-CString

And looking at the source, it shows that the `CString` is created with a new
owned memory allocation:
https://rust.docs.kernel.org/src/kernel/str.rs.html#878-890

Remo