@trusted assumptions about @safe code

Paul Backus snarwin at gmail.com
Mon May 25 23:25:24 UTC 2020


On Monday, 25 May 2020 at 23:04:49 UTC, ag0aep6g wrote:
> Deep in the discussion thread for DIP 1028 there is this little 
> remark by Zoadian [1]:
>
>> you can break previously verified @trusted code by just 
>> writing @safe code today.
>
> That statement fits something that occurred to me when trying 
> to lock down the definition of "safe interfaces" [2].
>
> Consider this little program that prints the address and first 
> character of a string in a convoluted way:
>
>     import std.stdio;
>     char f(string s) @trusted
>     {
>         immutable(char)* c = s.ptr;
>         writeln(g(* cast(size_t*) &c));
>         return *c;
>     }
>     size_t g(ref size_t s) @safe
>     {
>         return s;
>     }
>     void main() @safe
>     {
>         writeln(f("foo"));
>     }
>
> As the spec stands, I believe it allows f to be @trusted. The 
> function doesn't exhibit undefined behavior, and it doesn't 
> leak any unsafe values or unsafe aliasing. So it has a safe 
> interface and can be @trusted.
>
> With f correctly @trusted and everything else being @safe, that 
> code is good to go safety-wise.

My reading of the spec is that f violates this requirement of 
safe interfaces:

> 3. it cannot introduce unsafe aliasing that is accessible from 
> other parts of the program.

"Other parts of the program," taken at face value, should include 
both f's callers (direct and indirect) as well as any functions 
it calls (directly or indirectly). Since f introduces unsafe 
aliasing, and makes that aliasing visible to g, it should not be 
marked as @trusted.

I suppose it depends on exactly what is meant by "accessible"--if 
it refers to the aliased memory location, then my interpretation 
follows, but if it refers to the pointers, there's an argument to 
be made that f is fine, since only one of the pointers escapes.


More information about the Digitalmars-d mailing list