[fpc-devel] Const optimization is a serious bug
Florian Klaempfl
florian at freepascal.org
Tue Jul 5 17:28:41 CEST 2011
Am 04.07.2011 22:39, schrieb Chad Berchek:
> I've been reading over some of the recent discussion about reference
> counting problems with const string parameters. I've done some
> experiments and I believe that the so-called const optimization is a
> serious flaw, not just a corner case of questionable legitimacy. I have
> some sample code I will show which should be quite scary. Additionally,
> this is a security vulnerability. It is also a quiet bug, because it may
> go undetected for a long time but randomly result in unreproducible
> crashes.
>
> Consider:
> * It does not affect just global variables but also object fields. While
> global variables are used rarely, object fields are used constantly in OOP.
> * It does not affect just strings but also interfaces and dynamic arrays.
It affects more types, even shortstring suffers from it, the program
does not crash but might behave not as expected (similiar examples can
be created for normal arrays or records as well):
var
s : shortstring;
procedure p(const s1 : shortstring);
begin
s:='Ops';
writeln(s1);
end;
begin
s:='Hello world';
p(s);
end.
I see it only as a either or all or none: either the const optimization
is done for no types or for all types where it's useful. Everything else
is even more dangerous (if you consider this behaviour as dangerous)
because the outcome is unpredictible. However, I doubt that people will
be happy, if huge data arrays, records or shortstrings are always copied
and no const optimization is carried out.
As written in some of the bug reports, I consider as a better solution:
- Pointer checking of constant parameters of types like ansistrings,
interfaces at procedure exit. Together with heaptrc and keep_released
enabled, this catches all cases of disposed const parameters and
probably a lot more pointer errors.
- Like the scrambling of local parameters with -gttt, some checksumming
for contant parameters could be implemented. This catches not only the
modified constant parameter but also aliasing problems.
More information about the fpc-devel
mailing list