v icon indicating copy to clipboard operation
v copied to clipboard

Undefined behavior via signed integer overflow

Open andersk opened this issue 2 years ago • 2 comments

V version: V 0.3.0 1b46383.f0cee25 OS: linux, Linux version 5.18.6 (nixbld@localhost) (gcc (GCC) 11.3.0, GNU ld (GNU Binutils) 2.38) #1-NixOS SMP PREEMPT_DYNAMIC Wed Jun 22 12:28:13 UTC 2022

The home page claims that V has “No undefined behavior”. This code, however, has undefined behavior, because it compiles to C code with signed integer overflow, which is undefined behavior in C.

$ cat test.v
fn add(x int, y int) int {
    return x + y
}

fn main() {
    println(add(1, 2147483647))
}

$ v -cc gcc -cflags -fsanitize=undefined run test.v
/tmp/v_1000/test.15102990841247977677.tmp.c:12047:6: runtime error: signed integer overflow: 1 + 2147483647 cannot be represented in type 'int'
/tmp/v_1000/test.15102990841247977677.tmp.c:7551:33: runtime error: signed integer overflow: -2147483648 - 2147483600 cannot be represented in type 'int'
-2147483648

Of the two sanitizer errors reported here, the first is my x + y expression, and the second is within the int.str_l builtin.

https://github.com/vlang/v/blob/f0cee25213e25289ae4c60ba9a6a12e4aadf5e9d/vlib/builtin/int.v#L64

An example of an unexpected optimization that occurs due to undefined behavior:

$ cat test.v
fn add(x int, y int) int {
    return x + y
}

fn f(x int) bool {
    return x + 1 > x
}

fn g(x int) bool {
    return add(x, 1) > x
}

fn main() {
    x := 2147483647
    println(f(x))
    println(g(x))
}

$ ./v -cc gcc run test.v
true
false

andersk avatar Jul 01 '22 18:07 andersk

Isn't this issue resolved and should be closed?

Wajinn avatar Feb 06 '23 08:02 Wajinn

No. Just tried on Linux, and I get the same errors.

JalonSolov avatar Feb 06 '23 12:02 JalonSolov