On Friday, 24 May 2019 at 16:51:11 UTC, ag0aep6g wrote:
On 24.05.19 18:19, Atila Neves wrote:
On Friday, 24 May 2019 at 13:30:05 UTC, ag0aep6g wrote:
[...]
My `puts`s might not do any harm, but they could just as well be buffer overflows.

Could you please give an example of how @system allocator code could do that?

Sure. You just write beyond some buffer instead of calling `puts`:

----
char[3] buf;
char[3] foo = "foo";
char[3] bar = "bar";

struct UnsafeAllocator
{
    import std.experimental.allocator.mallocator: Mallocator;
    static instance = UnsafeAllocator.init;
    size_t i;
    void deallocate(void[] bytes) @nogc @system
    {
        buf.ptr[i .. i + 3] = '!';
        Mallocator.instance.deallocate(bytes);
    }
    void[] allocate(size_t sz) @nogc @system
    {
        buf.ptr[i .. i + 3] = '!';
        return Mallocator.instance.allocate(sz);
    }
}

void main() @safe @nogc
{
    {
        import nogc: BUFFER_SIZE, text;
        UnsafeAllocator.instance.i = 8;
            /* greater than buf.length, whoops */
        auto t = text!(BUFFER_SIZE, UnsafeAllocator)(42);
        assert(foo == "foo"); /* fails */
        UnsafeAllocator.instance.i = 16;
            /* also greater than buf.length, whoops again */
    }
    assert(bar == "bar"); /* fails */
}
----

You just can't trust user-provided @system code. It doesn't matter if it's allocator code or whatever.

I don't see the problem here. This example would throw RangeError at runtime instead of actually overwriting memory unless bounds checking is turned off.

The other issue is that Mallocator has a @safe allocate function and a @system deallocate function since it's up to the user of the interface to supply a slice that was actually malloc'ed. It's clear that this interface is one that can be used @safely (and is by automem.vector.Vector). Likewise, reallocating is @system because there might be references to the old pointer, but it makes sense that a @trusted block could exist where the reviewer makes sure that there's only ever one reference to the allocated memory.

Then there's the fact that if a 3rd party library really does want to corrupt memory they can just tag all their functions with @trusted, and unless someone looks at their code nobody will be the wiser.

Reply via email to