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.

That's right. If you are wrapping code that is provided by a third party, you should not mark any code as @trusted that makes calls to the third party library. By doing this, you are saying "any third party code I call is memory safe (source: dude just trust me)". That may work in the case where this third party code is set in stone and has been hand-audited by either you or the maintainers (ideally both), but you're accepting any implementation through a template argument. Doing this is extremely dangerous, because you're making memory safety promises about every single Allocator implementation in existence, in the present AND for the future.

What you have to do is leave the functions that make these calls unmarked (no @system, @trusted OR @safe), and allow the compiler to infer it based on the whether the third party implementation is @system/@trusted/@safe. That's the only sane way I can think of to do this.

Reply via email to