Re: [PATCH v5 04/26] rust: alloc: implement `Allocator` for `Kmalloc`

From: Danilo Krummrich
Date: Wed Aug 14 2024 - 13:13:31 EST


On Wed, Aug 14, 2024 at 04:28:04PM +0000, Benno Lossin wrote:
> On 12.08.24 20:22, Danilo Krummrich wrote:
> > +unsafe impl Allocator for Kmalloc {
>
> There is a missing SAFETY comment here (and also for Vmalloc, probably
> also for VKmalloc then).

Any suggestion on what to write here?

I'd probably come up with something like:

--
Memory returned from `Kmalloc` remains valid until explicitly freed.

It is valid to pass any pointer to an allocated memory buffer obtained with any
function of `Kmalloc` to any other function of `Kmalloc`.

If `Kmalloc::realloc` is called with a size of zero, the given memory
allocation, if any, is freed.

If `Kmalloc::realloc` is called with `None` it behaves like `Kmalloc::alloc`,
i.e. a new memory allocation is created.
--

and repeat that for `Vmalloc` and `KVmalloc`.

I'm not sure how useful that is though.

>
> ---
> Cheers,
> Benno
>
> > + unsafe fn realloc(
> > + ptr: Option<NonNull<u8>>,
> > + layout: Layout,
> > + flags: Flags,
> > + ) -> Result<NonNull<[u8]>, AllocError> {
> > + // SAFETY: `ReallocFunc::call` has the same safety requirements as `Allocator::realloc`.
> > + unsafe { ReallocFunc::KREALLOC.call(ptr, layout, flags) }
> > + }
> > +}
> > +
> > unsafe impl GlobalAlloc for Kmalloc {
> > unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
> > // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety
> > --
> > 2.45.2
> >
>