Discussion Thread: DIP 1035-- at system Variables--Final Review

Paul Backus snarwin at gmail.com
Wed Feb 23 18:16:17 UTC 2022


On Wednesday, 23 February 2022 at 00:14:13 UTC, Stanislav Blinov 
wrote:
> On Tuesday, 22 February 2022 at 18:33:58 UTC, Paul Backus wrote:
>> If you believe there is some way to get the above program to 
>> produce undefined behavior, or to complete your original 
>> example in such a way that it produces undefined behavior 
>> without the use of incorrect `@trusted` code, I'm afraid you 
>> will have to spell it out for me.
>
> Not exhaustive:
> It may corrupt a given GC's implementation's heap, which means 
> what occurs after the } is anyone's guess.
> It may mutate data that's supposed to be immutable (i.e. in a 
> parent process, though you could argue that might not be 
> relevant to the DIP).
> It may block indefinitely, or crash, or complete with no effect.
>
> If you could demonstrate that it cannot possibly exhibit at 
> least the above, I'll happily accept being mistaken.

Having spent some more time scratching my head over this, I now 
realize what I was missing: it is indeed possible to open a file 
descriptor that can corrupt *arbitrary* memory in a process's 
address space, using something like `/proc/self/mem`. Maybe I'm 
an idiot for missing this the first time around; I can only ask 
that you take pity on me. :)

This means that calling `write` on a fd is only memory safe if 
you have previously verified that the file the fd refers to is 
"well behaved" (i.e., satisfies a particular invariant). It 
follows that the fd itself must be stored in a `@system` variable 
in order to ensure that the invariant is maintained in `@safe` 
code.

I don't think adding `scope` checking to the fd makes any 
difference here, though. *Reading* from `/proc/self/mem` in 
`@safe` code is perfectly fine, even if you are reading from 
uninitialized or deallocated memory. The reason such reads are UB 
when done through pointers is that *dereferencing an invalid 
pointer* is UB, not because reading from the memory is UB.

(I'm also not sure if it's possible in practice to tell whether a 
file is "well behaved". If not, that means we have to either 
accept that `write` is *always* `@system`, or allow a permanent 
loophole in `@safe`. But that's a separate issue.)


More information about the Digitalmars-d mailing list