Re: [PATCH v4 09/28] rust: alloc: implement kernel `Box`

From: Benno Lossin
Date: Thu Aug 08 2024 - 15:44:34 EST


On 08.08.24 19:44, Danilo Krummrich wrote:
> On Wed, Aug 07, 2024 at 07:49:31AM +0000, Benno Lossin wrote:
>>>>> +impl<T, A> Drop for Box<T, A>
>>>>> +where
>>>>> + T: ?Sized,
>>>>> + A: Allocator,
>>>>> +{
>>>>> + fn drop(&mut self) {
>>>>> + let ptr = self.0.as_ptr();
>>>>> +
>>>>> + // SAFETY: `ptr` is always properly aligned, dereferenceable and points to an initialized
>>>>> + // instance of `T`.
>>>>> + let size = unsafe { core::mem::size_of_val(&*ptr) };
>>>>
>>>> 1. `size_of_val` is not `unsafe`.
>>>
>>> Right, but dereferencing the `ptr` is unsafe.
>>>
>>>> 2. why not use `&*self` instead of using the raw pointer? (then move the
>>>> let binding below this line)
>>>
>>> If we ever support non-ZST `Allocator`s using `self` would not always evaluate
>>> to the correct size. I think evaluating the size of `T` rather than `Box<T>` is
>>> the correct thing to do.
>>
>> I mean use `Box::deref` (that's what `&*self` should do), you don't need
>
> Actually, this must either be `size_of_val(&**self)` or `size_of_val::<T>(self).
>
> `size_of_val(&*self)` should indeed resolve to `&Box<T, A>`, right?

Oh yeah that is true, good catch! Here is a playground example [1].

[1]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c439494a0582bb287232c7a05e21bd23

---
Cheers,
Benno

>
>> to repeat the same SAFETY comment when it already is wrapped by a safe
>> function.
>>
>> ---
>> Cheers,
>> Benno
>>