Memory safe in D - cppfront/C++

Nick Treleaven nick at geany.org
Thu Apr 11 16:19:52 UTC 2024


On Monday, 1 April 2024 at 01:00:31 UTC, Walter Bright wrote:
> On 3/30/2024 2:38 AM, Nick Treleaven wrote:
>> cppfront:
>
> Is cppfront using ad-hoc or DFA? You can get a ways with 
> ad-hoc, but there's a reason optimizers use DFA, especially 
> with unstructured code.

 From what I have gathered, cppfront is only doing 2 basic things 
at the moment:
* require initialization on both branches of an `if` statement or 
neither
* track at runtime whether a variable has been initialized and 
abort if it is accessed without initialization

However, proper analysis is planned to detect common cases of 
invalid pointers and container types. It does not aim to catch 
all possible errors. See the links here which are for C++1:
https://github.com/hsutter/cppfront?tab=readme-ov-file#2015-lifetime-safety

Each point where a pointer variable is modified, the compiler 
tracks what possible things it could point to, e.g. local data. 
For the latter, when the local data goes out of scope, if the 
pointer hasn't been overwritten, then it is known to be pointing 
to invalid data and any subsequent dereference is flagged at 
compile-time. A partial prototype was implemented for Clang which 
was demo'd in the 2018 youtube video. There is also a formal 
written proposal P1179.

There is a section in that paper on loops - see 2.4.9:

> A loop is treated as if it were the first two loop iterations 
> unrolled using an if. For example,
`for(/*init*/;/*cond*/;/*incr*/){/*body*/}` is treated as 
`if(/*init*/;/*cond*/){/*body*/;/*incr*/}
if(/*cond*/){/*body*/}`.

There was a section on null dereference detection in the 2018 
video:
https://youtu.be/80BZxujhY38?t=41m22s

At around the 45m mark Herb actually says "there is no DFA going 
on". The example there has a loop whose number of iterations is 
only known at runtime.

Just before that null bit there was also an example that detects 
iterator invalidation.

>> Goto skipping initialization is already disallowed in D.
>
> That restriction is imposed because the front end doesn't do 
> DFA.

D already does enforce for aggregate constructors that immutable 
data is only initialized once. That AIUI is not really DFA, but 
something simpler, and the idea could be extended to all 
functions to detect common cases of uninitialized non-null 
reference types (if we had them) - at some speed cost, hopefully 
acceptable.


More information about the Digitalmars-d mailing list