JDK-6779290 : Casts in SharedRuntime::f2i, f2l, d2i and d2l rely on undefined behaviour
  • Type: Bug
  • Component: hotspot
  • Sub-Component: runtime
  • Affected Version: 7
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: linux
  • CPU: x86
  • Submitted: 2008-12-02
  • Updated: 2010-07-29
  • Resolved: 2008-12-23
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
Seen in OpenJDK6 b12 and OpenJDK7 tip.

FULL OS VERSION :
All platforms

A DESCRIPTION OF THE PROBLEM :
The various float-integer conversion routines in SharedRuntime -- f2i, f2l, d2i and d2l -- rely on undefined behaviour in the C++ specification, specifically the result of casting a floating point value to an integer value when the integer representation of the floating point value is too large to fit in the result type.  In addition, f2i and d2i cast signed 64-bit values to signed 32-bit values; the result of this action when the 64-bit value does not fit in the 32-bit type is also undefined.

THE PROBLEM WAS REPRODUCIBLE WITH -Xint FLAG: Did not try

THE PROBLEM WAS REPRODUCIBLE WITH -server FLAG: Did not try

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
The testcase at http://icedtea.classpath.org/bugzilla/attachment.cgi?id=131 contains the functions from SharedRuntime in a simple wrapper that calls the float and double functions with positive and negative infinities.

EXPECTED VERSUS ACTUAL BEHAVIOR :
  The result of compiling and testing it should be:

  $ gcc -o Test Test.c && ./Test
  0x80000000, 0x8000000000000000
  0x80000000, 0x8000000000000000
  0x7fffffff, 0x7fffffffffffffff
  0x7fffffff, 0x7fffffffffffffff

However on some platforms it is not.  One specific failure is with gcc 4.1.2 on Linux on 32-bit PowerPC; in this case you'll see this:

  $ gcc -o Test Test.c && ./Test
  0x00000001, 0x0000000000000001
  0x00000001, 0x0000000000000001
  0xffffffff, 0xffffffffffffffff
  0xffffffff, 0xffffffffffffffff
REPRODUCIBILITY :
This bug can be reproduced always.

CUSTOMER SUBMITTED WORKAROUND :
The patch at http://icedtea.classpath.org/bugzilla/attachment.cgi?id=132 replaces SharedRuntime::f2i et al with versions that should work regardless of the compiler, operating system, or CPU architecture.