Re: BUG #5416: int4inc() is wrong - Mailing list pgsql-bugs

From Tom Lane
Subject Re: BUG #5416: int4inc() is wrong
Date
Msg-id 16153.1271284822@sss.pgh.pa.us
Whole thread Raw
In response to Re: BUG #5416: int4inc() is wrong  (John Regehr <regehr@cs.utah.edu>)
Responses Re: BUG #5416: int4inc() is wrong
List pgsql-bugs
John Regehr <regehr@cs.utah.edu> writes:
> Hi Tom,
>> None of these proposals are improvements over what's there.  The
>> fundamental problem is that if the compiler chooses to believe that
>> overflow doesn't exist, it can optimize away *any* test that could only
>> succeed in overflow cases.  Finding a form of the test that fails to be
>> optimized away by today's version of gcc doesn't protect you against
>> tomorrow's version.

> Your assessment is not quite correct.  The existing function -- when passed
> INT_MAX as the argument -- executes an operation with undefined behavior,
> and a correct C compiler can optimize away the check.

> The alternate tests do not execute operations with undefined behavior for
> any argument value.

No, you're missing the point.  int4inc() could be rewritten with a test
for INT_MAX or similar, because its overflow behavior is so trivial:
there is exactly one, well-known, input value that is troublesome.
However, this is not so easy for any of the other arithmetic operations.
We need an approach that results in sane code and sane behavior for all
those places, and there's no point in making int4inc() follow a
different coding style than is used in the other functions.

It might be worth pointing out that we prefer to avoid explicit uses of
INT_MAX, or similar hard-wired assumptions about exactly how wide the
datatypes are.  This is so that the code won't fail if someday "int"
is not the same as "int32", for instance.  The issue is already quite
pressing for int64, which corresponds to different native C types on
different platforms.

If you can show me rewrites of all the basic arithmetic operations that
detect overflow in full compliance with the C standard, and are
readable, portable, and efficient, I'm all ears.  At the moment, though,
I regard the notion that C compilers can assume no overflow as pure
brain damage on the part of the spec authors and the compiler authors.
The real world is not like that.

            regards, tom lane

pgsql-bugs by date:

Previous
From: Tom Lane
Date:
Subject: Re: Bug in CREATE FUNCTION with character type (CONFIRMED BUG)
Next
From: "Kevin J Bluck"
Date:
Subject: Re: Bug in CREATE FUNCTION with character type (CONFIRMED BUG)