@system blocks and safer @trusted (ST) functions

claptrap clap at trap.com
Mon Jul 26 16:26:53 UTC 2021


On Monday, 26 July 2021 at 13:58:46 UTC, Paul Backus wrote:
> On Monday, 26 July 2021 at 09:39:57 UTC, claptrap wrote:
>> On Monday, 26 July 2021 at 07:32:24 UTC, Paul Backus wrote:
>>>
>>> @trusted code is correct if and only if it cannot possibly 
>>> allow undefined behavior to be invoked in @safe code.
>>
>> Your example doesn't invoke undefined behaviour in safe code, 
>> it invokes undefined behaviour in system code. The UB is in 
>> the system block. The memory corruption happens in the system 
>> block. After that all bets are off.
>
> Well, it is in a `@trusted` function, which is callable from 
> `@safe` code, so any undefined behavior in the `@system` block 
> is also possible undefined behavior in `@safe` code.
>
> If you can write a call to `favoriteElement` from `@safe` code 
> that causes UB, that would be sufficient to demonstrate that it 
> is not memory safe. Of course, it only counts as a mistake in 
> my example if you use the version I wrote, not your own 
> modified version. :)

Its a pointless exercise because your example is a red herring, 
but this breaks it.

```d
ref int[50] ohYeah() @trusted
{
     return *(cast(int[50]*) 123456);
}

int redHerring() @safe
{
     return favoriteElement(ohYeah());
}
```

See what we've learnt? That trusted / system etc can break 
safety. Top down, or bottom up. Its a house of cards, you cant 
escape that, unless you get rid of trusted and system completely.

Who knew? :)

Another way to think about it is that you are conflating "memory 
safe by convention" with "memory safe by compiler". Your example 
is memory safe by convention, IE, it is only so because the 
programmer has checked favouriteNumber doesnt break 
favouriteElement. So when you change favouriteNumber to 52 you 
are violating "safe by convention". You are not violating "safe 
by compiler". IE when you change favouriteNumber it doesnt change 
anything in terms of what is checked by the compiler. Or in terms 
of runtime checks. At least AFAIK.

I wonder what it is you expect the compiler to do.

And TBH I'm not even sure what your overall point is.


More information about the Digitalmars-d mailing list