[Issue 19916] union member access should be un- at safe

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu May 30 10:54:48 UTC 2019


https://issues.dlang.org/show_bug.cgi?id=19916

--- Comment #8 from Simen Kjaeraas <simen.kjaras at gmail.com> ---
(In reply to Dennis from comment #7)
> Unless there is a way to actually corrupt memory in @safe code using this
> (without using @trusted) it's not something @safe should prevent.

Did you see my example code? NotAPointer is perfectly safe to use in @safe
code, and presents an interface that encodes that. To reiterate, this may be
weird code, but it should be perfectly fine to use in @safe:

struct NotAPointer {
    private static int* p = null;
    private static int len;

    private static void initialize() {
        import core.stdc.stdlib;
        len = 100;
        p = cast(int*)malloc(int.sizeof*len);
    }

    int idx;
    @disable this();
    @trusted this(int i) {
        if (p is null) initialize();
        assert(i >= 0 && i < len);
        idx = i;
    }
    @trusted void callMethod() {
        // We know idx can only be set by the constructor, which checks that 
        // it's valid, and initializes p correctly, so no bounds check is
        // necessary at this point.
        p[idx] = 3;
    }
}

There are currently only two ways to make that code do bad things in @safe
code, and that's unions and void initialization:


@safe unittest {
    NotAPointer p = void;
    p.callMethod();
}

@safe unittest {
    union U {
        int n;
        NotAPointer np;
    }
    U u = {10};
    u.np.callMethod();
}

--


More information about the Digitalmars-d-bugs mailing list