RFR (s) 8225397 : Integer value miscalculation in toString() method of BitSet

Andrew Haley aph at redhat.com
Thu Jun 6 10:57:49 UTC 2019


On 6/6/19 10:18 AM, Ivan Gerasimov wrote:
> Hello!
> 
> It is yet another instance of integer overflow under certain extreme 
> circumstances.
> 
> This time it is when calculating the initial capacity of a StringBuilder 
> in BitSet.toString.
> 
> If there are too many elements in the set, we can't do much anyway.
> 
> The best effort is to avoid confusing NegativeArraySizeException and let 
> the method throw OOM.
> 
> Would you please help review the fix?
> 
> BUGURL: https://bugs.openjdk.java.net/browse/JDK-8225397
> WEBREV: http://cr.openjdk.java.net/~igerasim/8225397/00/webrev/

@@ -1184,7 +1184,9 @@

         int numBits = (wordsInUse > 128) ?
             cardinality() : wordsInUse * BITS_PER_WORD;
-        StringBuilder b = new StringBuilder(6*numBits + 2);
+        int sizeHint = (numBits <= (Integer.MAX_VALUE - 22) / 6) ?
+            6 * numBits + 2 : Integer.MAX_VALUE - 20;
+        StringBuilder b = new StringBuilder(sizeHint);
         b.append('{');

         int i = nextSetBit(0);

This needs a comment. What is significant about 6 and 22?

-- 
Andrew Haley
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
https://keybase.io/andrewhaley
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671


More information about the core-libs-dev mailing list