dkorpel / dconf

Slides and demos from my DConf presentations
2 stars 0 forks source link

A problem in the arena allocator #1

Open dukc opened 1 month ago

dukc commented 1 month ago

I believe the arena allocator is not entirely memory safe as presented.

Becuase you could do something like this with it:

@safe void main()
{
    Arena a;
    auto arr = a.alloc.array!ubyte(0x4000);
        a.destroy();
        arr[] = 0xFF;
}

Assuming no language changes, the arena would be safe if it could only be used in a "borrow" callback, like the one needed to use SafeRefCounted safely.

Still cool concept though! I'd much rather have just one callback to instantiate one arena rather than several nested callbacks I'd have to do if I were making several SafeRefCounted allocations.

dkorpel commented 1 month ago

Thanks for pointing this out.

I consider this similar to Issue 21981 - Manually calling a __dtor can violate memory safety

We should be able to write @trusted destructors under the assumption that the object is not prematurely destructed in @safe code. Calling __dtor or destroy() should be @system.

dukc commented 1 month ago

We should be able to write @trusted destructors under the assumption that the object is not prematurely destructed in @safe code. Calling __dtor or destroy() should be @system.

Unfortunately I don't think that works. Or at least it's a really deep rabbit hole to prevent that:

auto pArena = new Arena();
auto arr = (*pArena).alloc!ubyte(0x4000);
pArena = null;
GC.collect();
arr[] = 0xFF;

Source: When I suggested the same 2½ years ago and realised I was wrong.