@trusted assumptions about @safe code
Dukc
ajieskola at gmail.com
Mon May 25 23:47:47 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.
No, `f` should be just dead `@system`. If you call f with a
string which does not point to null, but is empty, boom!
But for rest of the reply, I assume you meant a function that
could really be `@trusted` with all parameters.
>
> Now imagine that some time passes. Code gets added and shuffled
> around. Maybe g ends up in another module, far away from f. And
> as it happens, someone adds a line to g:
>
> size_t g(ref size_t s) @safe
> {
> s = 0xDEADBEEF; /* ! */
> return s;
> }
Credible scenario.
>
> g is still perfectly @safe, and there's not even any @trusted
> code in the vicinity to consider. So review comes to the
> conclusion that the change is fine safety-wise. But g violates
> an assumption in f. And with that broken assumption, memory
> safety comes crumbling down, "by just writing @safe code".
>
> I think that's a problem. Ideally, it should not be possible to
> cause memory corruption by adding a line to @safe code. But I
> know that I'm more nitpicky than many when it comes to that
> rule and @safe/@trusted in general.
I don't think it as a problem for `@safe`. `@safe` is just a
command to turn the memory checking tool on, not a code
certification (although using @safe where possible would probably
be required for certifying). Combating the scenarios you
mentioned means that the `@safe` function called must be at least
as certified as the `@trusted` caller, but that is no reason to
forbid using the memory checking tool the language offers.
More information about the Digitalmars-d
mailing list