2

Can Dafny model integer overflow? I was surprised when Dafny proved the following:

method overflow(c : int)
{
    if (c > 0)
    {
        assert((c+1) > 0);
    }
}

What am I missing?

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87

1 Answers1

1

The type int in Dafny means "mathematical integer". So there is no overflow.

If you want to model machine arithmetic, there are a few ways to do it.

One way is to define something like:

type uint64 = x:int | 0 <= x < 0x10000000000000000

and then when you try to store the result in a uint64 you will get an error:

method overflow(c: uint64) {
  if c > 0 {
    var d: uint64 := c + 1;
    assert d > 0;
  }
}

This technique is primarily useful for proving that your program does not overflow. If instead you want to reason about a program that intentionally uses two's complement arithmetic, you can do that by using bitvectors, like this:

method overflow(c: bv64) {
  if c > 0 {
    assert c + 1 > 0;
  }
}

Bitvectors are a relatively recent addition to Dafny (ok, not that recent, but in the past few years), and in my experience they are not widely used unless you are specifically reasoning about a piece of code that does bitwise operations (eg, crypto). I would recommend staying away from bitvectors if at all possible.

James Wilcox
  • 5,307
  • 16
  • 25
  • I have a scenario where I actually *want* the integers to overflow, I encoded it using bit vectors and there seems to be a bug there (?) Here is the permalink: https://rise4fun.com/Dafny/cMPs and here is the shortest example I could think of: `method wrong(a : bv32, b : bv32){if ((a >= 1) || (b >= 1)) { return; } assert (a+b <= 0);}` dafny does not warn on assertion violation where in fact it is possible. – OrenIshShalom Sep 16 '20 at 16:30
  • 1
    I think bitvectors are unsigned in Dafny. So the example you sent is correct because `a` and `b` must both be 0 if they are less than 1. – James Wilcox Sep 16 '20 at 16:39
  • 1
    Yes, bitvectors in Dafny are unsigned. Arithmetic operations on them will wrap. – Rustan Leino Sep 16 '20 at 18:06