Improving assert-printing in DMD
Kapps via Digitalmars-d
digitalmars-d at puremagic.com
Thu Oct 1 07:49:15 PDT 2015
On Tuesday, 29 September 2015 at 21:26:00 UTC, John Colvin wrote:
> Not necessarily. It could just be a defensive assert for
> something that should already have been verified/cleaned/caught
> earlier.
>
> auto pass = getPassword();
> pass.clean();
> assert(pass == pass.toLower());
> //and on we go ...
There are a few flaws with this:
First, your assert applies only in debug mode. You're likely not
deploying your service in debug mode, so your attempt at
defensive programming does nothing to protect you when you
actually need it.
Second, and more critical, the way assert is apparently intended
to be, is a guarantee that can be used towards optimization. The
existence of an assert means that that situation can *never*
happen. You take your existing code, and then later on you decide
that an assert isn't enough so you add another check for release
mode. In which case (as far as I understand it), you run into the
following situation:
auto pass = getPassword();
pass.clean();
assert(pass == pass.toLower());
// Later on...
enforce(pass == pass.toLower());
Now not only is your assert not triggered because you're in
release mode, but that assert provides a guarantee to the
compiler that pass is *always* equal to pass.toLower, causing the
compiler to optimize out that enforce call as it's redundant.
Therefore, your assert does nothing, and your enforce now does
nothing as well, masking a potential vulnerability.
More information about the Digitalmars-d
mailing list