On Wed, Aug 29, 2012 at 01:24:39PM +0200, Stefan Marr wrote:
Hi Nicolas:
On 29 Aug 2012, at 12:18, Nicolas Cellier wrote:
Beside these bugs, when I read the code, I'm quite sure it's a nest of future bugs because there are many other attempts to catch overflow in post-condition (like testing that addition of two positive is negative when an underflow occurs) that technically rely on explicitely Undefined Behaviour (UB).
See below. Tests such as this are essential, and they they do *not* rely on undefined behavior if the C variables are properly declared.
I guess http://forum.world.st/Is-bytecodePrimMultiply-correct-td3869580.html is related too. I am not sure whether that got changed in the VMs, but sounds very much like the same kind of problem. (undefined behavior and overflows)
Since C is undefined in that regard, what are the options? Hand-crafted assembly for all relevant platforms? Are there libraries that abstract from these things?
A good general solution is to perform the arithmetic using variables declared as, or cast to, unsigned. The ambiguity in C language pertains only to signed twos complement arithmetic, so if the operations are performed on twos complement values that are declared unsigned, then no compiler optimization is possible and the results are unambiguous regardless of compiler behavior. Results of the unsigned operations may be tested for overflow, then cast back to signed integer if the result is intended to be interpreted as a signed integer.
Dave