[Issue 21565] New: @safe code allows modification of a scalar that overlaps with a pointer

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Jan 20 19:30:39 UTC 2021


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

          Issue ID: 21565
           Summary: @safe code allows modification of a scalar that
                    overlaps with a pointer
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: safe, spec
          Severity: major
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: schveiguy at gmail.com

According to https://dlang.org/spec/function.html#safe-aliasing

It states:

When one memory location is accessible with two different types, that aliasing
is considered safe if:

1. both types are const or immutable; or
2. one of the types is mutable while the other is a const-qualified basic data
type; or
3. both types are mutable basic data types; or
4. one of the types is a static array type with length zero; or
5. one of the types is a static array type with non-zero length, and aliasing
of the array's element type and the other type is safe; or
6. both types are pointer types, and aliasing of the target types is safe, and
the target types have the same size.

All other cases of aliasing are considered unsafe.

However, if you access a scalar overlapping a pointer, the access and even
mutation of the scalar is considered @safe by the compiler:

union T {int x; int *y;}

void main() @safe
{
    T t;
    t.x = 5;
    // *t.y = 5; // error in @safe, but not in @trusted
}

Such access should be considered illegal as it does not fit into any of the
categories. 1, 2, 4, 5, and 6 trivially do not apply. Whether int * is
considered a "basic type" is possibly open to interpretation, but I would say
it is not, considering that if it were, then rule 2 would allow arbitrary
pointer usage. This disqualifies 3, or at least suggests an edit is in order.

One might suggest that there is no harm in allowing mutating a scalar that
overlaps with a pointer if the pointer cannot be accessed. But this is a naive
view of code. Not all code is @safe, and if @trusted code cannot be reasoned
about without also having to manually verify all @safe code, then there is no
point to @trusted code.

The access should be disallowed.

--


More information about the Digitalmars-d-bugs mailing list