@trusted assumptions about @safe code

Paolo Invernizzi paolo.invernizzi at gmail.com
Wed May 27 05:57:36 UTC 2020


On Wednesday, 27 May 2020 at 00:50:26 UTC, Paul Backus wrote:
> On Tuesday, 26 May 2020 at 22:52:09 UTC, ag0aep6g wrote:
>> But yeah, the @trusted function might rely on the @safe 
>> function returning 42. And when it suddenly returns 43, all 
>> hell breaks loose. There doesn't need to be any monkey 
>> business with unsafe aliasing or such. Just an @safe function 
>> returning an unexpected value.
>>
>> I suppose the only ways to catch that kind of thing would be 
>> to forbid calling @safe (and other @trusted?) functions from 
>> @trusted (and @system?) code, or to mandate that the exact 
>> behavior of @safe functions (including their return values) 
>> cannot be relied upon for safety. Those would be really, 
>> really tough sells.
>
> All that's necessary is to have the @trusted function check 
> that the assumption it's relying on is actually true:
>
> @safe int foo() { ... }
>
> @trusted void bar() {
>     int fooResult = foo();
>     assert(fooResult == 42);
>     // proceed accordingly
> }
>
> If the assumption is violated, the program will crash at 
> runtime rather than potentially corrupt memory.

Exactly: the whole point in trusted it’s that it MUST check the 
parameters it’s using to call system code, and with an assert 
that’s just fine in this case, as it’s checking invariants in the 
program logic.

The only way for a safe program to corrupt memory should be 
inside the external system code binary: a bug in a used system 
library, a misunderstanding of the API documentation, and so on.




More information about the Digitalmars-d mailing list