Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

immutability hole related to context pointers accessed through const pure methods #19405

Open
dlangBugzillaToGithub opened this issue Mar 6, 2018 · 2 comments

Comments

@dlangBugzillaToGithub
Copy link

timon.gehr reported this on 2018-03-06T22:27:00Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=18567

CC List

  • RazvanN

Description

DMD 2.079.0

void main(){
    int i = 0;
    struct S{
        const(int)* fun()const pure{
	    return &i;
        }
    }
    immutable S s;
    static const(int)* foo(immutable(S) s)pure{
	    return s.fun();
    }
    immutable(int) *pi=foo(s);
    import std.stdio;
    writeln(*pi); // 0
    i+=1;
    writeln(*pi); // 1
}

I.e. the data *pi is typed as immutable(int), yet changes.
@dlangBugzillaToGithub
Copy link
Author

razvan.nitu1305 commented on 2022-07-29T09:21:23Z

The code now compiles and prints:

```
0
0
```

So `i` does not change anymore, however, the code is still broken in my opinion, as it should not compile. Since `s` is immutable, maybe the context pointer for fun should also be type as immutable?

@dlangBugzillaToGithub
Copy link
Author

timon.gehr commented on 2022-07-29T10:00:30Z

Well, the compiler is just compiling the code differently now (which it can do, as it exhibits UB), the CSE is pretty easy to defeat though:

void main(){
    int i = 0;
    struct S{
        const(int)* fun()const pure{
	    return &i;
        }
    }
    immutable S s;
    static const(int)* foo(immutable(S) s)pure{
	    return s.fun();
    }
    immutable(int) *pi=foo(s);
    import std.stdio;
    writeln(*pi); // 0
    i+=1;
    int x=*pi;
    writeln(x); // 1
}


The problem is that this line compiles:

immutable S s;

This requires an immutable context pointer, but a mutable one is provided.

In general, context pointers should be type checked essentially as if we were passing around explicit pointers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant