Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does static analysis ignore double <= and >= requirement?

I have a very simple class utilizing .NET Code Contracts:

public class ContractSquareRoot
{
    /// <summary>
    /// Makes your life much easier by calling Math.Sqrt for you. Ain't that peachy.
    /// </summary>
    /// <param name="value">The value to calculate the square root from. No negatives!</param>
    /// <returns>The square root of the given value. Obviously always > 0.</returns>
    public double CalculateSquareRoot(double value)
    {
        Contract.Requires<ArgumentException>(0 <= value);
        Contract.Ensures(0 <= Contract.Result<double>());

        double squareRoot = Math.Sqrt(value);

        return squareRoot;
    }
}

When I call the method with a negative value, I expect the static code analysis to warn me about it.

class Program
{
    static void Main(string[] args)
    {

        var barMansSquareroot = new ContractSquareRoot();

        // This should not be possible...
        barMansSquareroot.CalculateSquareRoot(-42);

    }
}

But even if the Contract.Requires fails throwing the desired exception, the static code analysis marks every assertion as correct. Interestingly enough, it warns me about the violation when I change the type of value to int or if I replace <= with <. The misbehaviour is limited to double and float. I am assuming it has something to do with the precision of floating point values.

It even works when I formulate the requirement like this:

Contract.Requires<ArgumentException>(!(0 > value));

Is that a bug or am I doing something wrong?

like image 903
vlow Avatar asked Oct 09 '14 10:10

vlow


People also ask

Why is static analysis Important explain?

One of the primary reasons why (static application security testing) static analysis is so important is that it lets you thoroughly analyze all of your code without even executing it. It is because of this fact that it is able to detect vulnerabilities in even the most distant and unattended portions of the code also.

How do tools help in static testing and static analysis?

Static analysis tools are generally used by developers as part of the development and component testing process. The key aspect is that the code (or other artefact) is not executed or run but the tool itself is executed, and the source code we are interested in is the input data to the tool.


1 Answers

I hope you might missed to install Microsoft code contract.

You can download Microsoft Code Contracts from Microsoft Research: http://research.microsoft.com/en-us/projects/contracts/

Now on your project properties you will get an extra tab where you can set runtime and static checking.

like image 168
Joseph Avatar answered Oct 02 '22 12:10

Joseph