Re: [RFC PATCH] rust: alloc: pass `old_layout` to `Allocator`

From: Danilo Krummrich
Date: Tue Sep 24 2024 - 09:34:39 EST


On Tue, Sep 24, 2024 at 03:31:55PM +0200, Danilo Krummrich wrote:
> On Mon, Sep 23, 2024 at 05:13:15PM +0100, Gary Guo wrote:
> > On Mon, 23 Sep 2024 15:56:28 +0200
> > Alice Ryhl <aliceryhl@xxxxxxxxxx> wrote:
> >
> > > On Sat, Sep 21, 2024 at 5:33 PM Danilo Krummrich <dakr@xxxxxxxxxx> wrote:
> > > > @@ -84,11 +92,18 @@ unsafe fn call(
> > > > &self,
> > > > ptr: Option<NonNull<u8>>,
> > > > layout: Layout,
> > > > + old_layout: Layout,
> > > > flags: Flags,
> > > > ) -> Result<NonNull<[u8]>, AllocError> {
> > > > let size = aligned_size(layout);
> > > > let ptr = match ptr {
> > > > - Some(ptr) => ptr.as_ptr(),
> > > > + Some(ptr) => {
> > > > + if old_layout.size() == 0 {
> > > > + ptr::null()
> > > > + } else {
> > > > + ptr.as_ptr()
> > > > + }
> > > > + }
> > >
> > > This is making Allocator work with zero-sized types, which deviates
> > > from std. We should not do that without a reason. What is the reason?
> > >
> > > Alice
> >
> > As Benno said, this makes the API closer to Rust `allocator_api`
> > Allocator trait as opposed to deviation.
> >
> > There's one benefit of doing this (discussed with Danilo off-list),
> > which is it removes ZST special casing from caller. This RFC patch
> > simplifies `Box` handling, and if we add this line to the safety doc
> >
> > `ptr` does not need to be a pointer returned by this
> > allocator if the layout is zero-sized.
> >
> > then the `Vec` can also be simplified, removing all logics handling ZST
> > specially, except for `Vec::new()` which it forges a well-aligned
> > dangling pointer from nowhere.
>
> Partially, we still need the additional `Layout` for `Allocator::free`, which
> in `Vec::drop` and `IntoIter::drop` looks like this:
>
> `let layout = Layout::array::<T>(self.cap).unwrap();`

Adding in the diff:

- // If `cap == 0` we never allocated any memory in the first place.
- if self.cap != 0 {
- // SAFETY: `self.ptr` was previously allocated with `A`.
- unsafe { A::free(self.ptr.cast()) };
- }
+ // This can never fail; since this `Layout` is equivalent to the one of the original
+ // allocation.
+ let layout = Layout::array::<T>(self.cap).unwrap();
+
+ // SAFETY: `self.ptr` was previously allocated with `A`.
+ unsafe { A::free(self.ptr.cast(), layout) };

>
> I really dislike that this can potentially transform into `BUG()`, but that's
> probably unrelated to this patch series.
>
> >
> > Best,
> > Gary
> >