Issue 20941 - __traits(getMember) should not allow safe code to access private fields
Summary: __traits(getMember) should not allow safe code to access private fields
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86 Mac OS X
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2020-06-17 12:38 UTC by Andrei Alexandrescu
Modified: 2022-12-17 10:31 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Andrei Alexandrescu 2020-06-17 12:38:03 UTC
This is taken from DIP 1035:

struct S {
    private union {
        int x;
        int* y;
    }
    private int tag; // x if 0, y if 1
    // public @trusted interface follows
    void set(int rhs) @trusted {
        if (tag == 0) x = rhs;
        else *y = rhs;
    }
    ....
}

Allowing safe code to modify tag from @safe code, followed by calling set(), results in unsafe code from safe functions.

This could be relaxed to restrict access only for types that have @trusted functions.
Comment 1 Stanislav Blinov 2020-06-17 20:18:57 UTC
For clarity, you mean modifying `tag` like so?

void unsafe() @safe
{
    S s;
    __traits(getMember, s, "tag") = 2; // should be error
    s.set(42);
}