changeset 8869:a32dc7400435

8179098: Crypto AES/ECB encryption/decryption performance regression (introduced in jdk9b73) 8135248: Add utility methods to check indexes and ranges 8142493: Utility methods to check indexes and ranges doesn't specify behavior when function produces null 8146458: Improve exception reporting for Objects.checkIndex/checkFromToIndex/checkFromIndexSize 8155794: Move Objects.checkIndex BiFunction accepting methods to an internal package Summary: Do bounds check per encryption/decryption call instead of per block Reviewed-by: mbalao
author andrew
date Mon, 15 Jul 2019 07:52:23 +0100
parents d15ed96035d0
children 2f920c764013
files src/share/classes/com/sun/crypto/provider/AESCrypt.java src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java src/share/classes/com/sun/crypto/provider/CipherFeedback.java src/share/classes/com/sun/crypto/provider/CounterMode.java src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java src/share/classes/com/sun/crypto/provider/OutputFeedback.java src/share/classes/com/sun/crypto/provider/PCBC.java src/share/classes/sun/security/util/ArrayUtil.java src/share/classes/sun/security/util/BiConsumer.java src/share/classes/sun/security/util/BiFunction.java src/share/classes/sun/security/util/IntSupplier.java src/share/classes/sun/security/util/Preconditions.java test/java/util/Objects/CheckIndex.java test/sun/security/util/math/TestIntegerModuloP.java
diffstat 14 files changed, 975 insertions(+), 82 deletions(-) [+]
line wrap: on
line diff
--- a/src/share/classes/com/sun/crypto/provider/AESCrypt.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/com/sun/crypto/provider/AESCrypt.java	Mon Jul 15 07:52:23 2019 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,6 @@
 
 import java.security.InvalidKeyException;
 import java.security.MessageDigest;
-import java.util.Objects;
 
 /**
  * Rijndael --pronounced Reindaal-- is a symmetric cipher with a 128-bit
@@ -348,8 +347,8 @@
      */
     void encryptBlock(byte[] in, int inOffset,
                       byte[] out, int outOffset) {
-        cryptBlockCheck(in, inOffset);
-        cryptBlockCheck(out, outOffset);
+        // Array bound checks are done in caller code, i.e.
+        // FeedbackCipher.encrypt/decrypt(...) to improve performance.
         implEncryptBlock(in, inOffset, out, outOffset);
     }
 
@@ -426,8 +425,8 @@
      */
     void decryptBlock(byte[] in, int inOffset,
                       byte[] out, int outOffset) {
-        cryptBlockCheck(in, inOffset);
-        cryptBlockCheck(out, outOffset);
+        // Array bound checks are done in caller code, i.e.
+        // FeedbackCipher.encrypt/decrypt(...) to improve performance.
         implDecryptBlock(in, inOffset, out, outOffset);
     }
 
@@ -588,26 +587,6 @@
         out[outOffset  ] = (byte)(Si[(a0       ) & 0xFF] ^ (t1       ));
     }
 
-    // Used to perform all checks required by the Java semantics
-    // (i.e., null checks and bounds checks) on the input parameters
-    // to encryptBlock and to decryptBlock.
-    // Normally, the Java Runtime performs these checks, however, as
-    // encryptBlock and decryptBlock are possibly replaced with
-    // compiler intrinsics, the JDK performs the required checks instead.
-    // Does not check accesses to class-internal (private) arrays.
-    private static void cryptBlockCheck(byte[] array, int offset) {
-        Objects.requireNonNull(array);
-
-        if (offset < 0 || offset >= array.length) {
-            throw new ArrayIndexOutOfBoundsException(offset);
-        }
-
-        int largestIndex = offset + AES_BLOCK_SIZE - 1;
-        if (largestIndex < 0 || largestIndex >= array.length) {
-            throw new ArrayIndexOutOfBoundsException(largestIndex);
-        }
-    }
-
     /**
      * Expand a user-supplied key material into a session key.
      *
--- a/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java	Mon Jul 15 07:52:23 2019 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 import java.security.ProviderException;
 import java.util.Objects;
 
+import sun.security.util.ArrayUtil;
 
 /**
  * This class represents ciphers in cipher block chaining (CBC) mode.
@@ -143,9 +144,9 @@
         if (plainLen <= 0) {
             return plainLen;
         }
-        cryptBlockSizeCheck(plainLen);
-        cryptNullAndBoundsCheck(plain, plainOffset, plainLen);
-        cryptNullAndBoundsCheck(cipher, cipherOffset, plainLen);
+        ArrayUtil.blockSizeCheck(plainLen, blockSize);
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, plainLen);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, plainLen);
         return implEncrypt(plain, plainOffset, plainLen,
                            cipher, cipherOffset);
     }
@@ -193,9 +194,9 @@
         if (cipherLen <= 0) {
             return cipherLen;
         }
-        cryptBlockSizeCheck(cipherLen);
-        cryptNullAndBoundsCheck(cipher, cipherOffset, cipherLen);
-        cryptNullAndBoundsCheck(plain, plainOffset, cipherLen);
+        ArrayUtil.blockSizeCheck(cipherLen, blockSize);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, cipherLen);
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, cipherLen);
         return implDecrypt(cipher, cipherOffset, cipherLen, plain, plainOffset);
     }
 
@@ -214,23 +215,4 @@
         }
         return cipherLen;
     }
-
-    private void cryptBlockSizeCheck(int len) {
-        if ((len % blockSize) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
-    }
-
-    private static void cryptNullAndBoundsCheck(byte[] array, int offset, int len) {
-        Objects.requireNonNull(array);
-
-        if (offset < 0 || offset >= array.length) {
-            throw new ArrayIndexOutOfBoundsException(offset);
-        }
-
-        int endIndex = offset + len - 1;
-        if (endIndex < 0 || endIndex >= array.length) {
-            throw new ArrayIndexOutOfBoundsException(endIndex);
-        }
-    }
 }
--- a/src/share/classes/com/sun/crypto/provider/CipherFeedback.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/com/sun/crypto/provider/CipherFeedback.java	Mon Jul 15 07:52:23 2019 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.security.InvalidKeyException;
 import java.security.ProviderException;
+import sun.security.util.ArrayUtil;
 
 /**
  * This class represents ciphers in cipher-feedback (CFB) mode.
@@ -149,9 +150,9 @@
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
                 byte[] cipher, int cipherOffset) {
-        if ((plainLen % numBytes) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
+        ArrayUtil.blockSizeCheck(plainLen, numBytes);
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, plainLen);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, plainLen);
 
         int nShift = blockSize - numBytes;
         int loopCount = plainLen / numBytes;
@@ -225,9 +226,10 @@
      */
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
                 byte[] plain, int plainOffset) {
-        if ((cipherLen % numBytes) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
+
+        ArrayUtil.blockSizeCheck(cipherLen, numBytes);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, cipherLen);
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, cipherLen);
 
         int nShift = blockSize - numBytes;
         int loopCount = cipherLen / numBytes;
--- a/src/share/classes/com/sun/crypto/provider/CounterMode.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/com/sun/crypto/provider/CounterMode.java	Mon Jul 15 07:52:23 2019 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.security.InvalidKeyException;
 
+import sun.security.util.ArrayUtil;
 
 /**
  * This class represents ciphers in counter (CTR) mode.
@@ -173,6 +174,10 @@
         if (len == 0) {
             return 0;
         }
+
+        ArrayUtil.nullAndBoundsCheck(in, inOff, len);
+        ArrayUtil.nullAndBoundsCheck(out, outOff, len);
+
         int result = len;
         while (len-- > 0) {
             if (used >= blockSize) {
--- a/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java	Mon Jul 15 07:52:23 2019 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.security.InvalidKeyException;
 import java.security.ProviderException;
+import sun.security.util.ArrayUtil;
 
 /**
  * This class represents ciphers in electronic codebook (ECB) mode.
@@ -112,9 +113,10 @@
      * @return the length of the encrypted data
      */
     int encrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
-        if ((len % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
+        ArrayUtil.blockSizeCheck(len, blockSize);
+        ArrayUtil.nullAndBoundsCheck(in, inOff, len);
+        ArrayUtil.nullAndBoundsCheck(out, outOff, len);
+
         for (int i = len; i >= blockSize; i -= blockSize) {
             embeddedCipher.encryptBlock(in, inOff, out, outOff);
             inOff += blockSize;
@@ -141,9 +143,10 @@
      * @return the length of the decrypted data
      */
     int decrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
-        if ((len % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
+        ArrayUtil.blockSizeCheck(len, blockSize);
+        ArrayUtil.nullAndBoundsCheck(in, inOff, len);
+        ArrayUtil.nullAndBoundsCheck(out, outOff, len);
+
         for (int i = len; i >= blockSize; i -= blockSize) {
             embeddedCipher.decryptBlock(in, inOff, out, outOff);
             inOff += blockSize;
--- a/src/share/classes/com/sun/crypto/provider/OutputFeedback.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/com/sun/crypto/provider/OutputFeedback.java	Mon Jul 15 07:52:23 2019 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.security.InvalidKeyException;
 import java.security.ProviderException;
+import sun.security.util.ArrayUtil;
 
 /**
  * This class represents ciphers in output-feedback (OFB) mode.
@@ -148,10 +149,10 @@
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
                 byte[] cipher, int cipherOffset) {
+        ArrayUtil.blockSizeCheck(plainLen, numBytes);
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, plainLen);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, plainLen);
 
-        if ((plainLen % numBytes) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
         int nShift = blockSize - numBytes;
         int loopCount = plainLen / numBytes;
 
@@ -189,6 +190,9 @@
      */
     int encryptFinal(byte[] plain, int plainOffset, int plainLen,
                      byte[] cipher, int cipherOffset) {
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, plainLen);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, plainLen);
+
         int oddBytes = plainLen % numBytes;
         int len = encrypt(plain, plainOffset, (plainLen - oddBytes),
                           cipher, cipherOffset);
--- a/src/share/classes/com/sun/crypto/provider/PCBC.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/com/sun/crypto/provider/PCBC.java	Mon Jul 15 07:52:23 2019 +0100
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.security.InvalidKeyException;
 import java.security.ProviderException;
+import sun.security.util.ArrayUtil;
 
 
 /**
@@ -136,9 +137,10 @@
     int encrypt(byte[] plain, int plainOffset, int plainLen,
                 byte[] cipher, int cipherOffset)
     {
-        if ((plainLen % blockSize) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
+        ArrayUtil.blockSizeCheck(plainLen, blockSize);
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, plainLen);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, plainLen);
+
         int i;
         int endIndex = plainOffset + plainLen;
 
@@ -176,9 +178,10 @@
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
                 byte[] plain, int plainOffset)
     {
-        if ((cipherLen % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
+        ArrayUtil.blockSizeCheck(cipherLen, blockSize);
+        ArrayUtil.nullAndBoundsCheck(cipher, cipherOffset, cipherLen);
+        ArrayUtil.nullAndBoundsCheck(plain, plainOffset, cipherLen);
+
         int i;
         int endIndex = cipherOffset + cipherLen;
 
--- a/src/share/classes/sun/security/util/ArrayUtil.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/src/share/classes/sun/security/util/ArrayUtil.java	Mon Jul 15 07:52:23 2019 +0100
@@ -25,12 +25,38 @@
 
 package sun.security.util;
 
+import java.util.List;
+import java.security.*;
+
 /**
  * This class holds the various utility methods for array range checks.
  */
 
 public final class ArrayUtil {
 
+    private static final Function<String, ArrayIndexOutOfBoundsException> aioobeGenerator =
+        new Function<String, ArrayIndexOutOfBoundsException>() {
+           @Override
+           public ArrayIndexOutOfBoundsException apply(String x) {
+               return new ArrayIndexOutOfBoundsException(x);
+           }
+        };
+
+    private static final BiFunction<String, List<Integer>,
+            ArrayIndexOutOfBoundsException> AIOOBE_SUPPLIER =
+            Preconditions.outOfBoundsExceptionFormatter(aioobeGenerator);
+
+    public static void blockSizeCheck(int len, int blockSize) {
+        if ((len % blockSize) != 0) {
+            throw new ProviderException("Internal error in input buffering");
+        }
+    }
+
+    public static void nullAndBoundsCheck(byte[] array, int offset, int len) {
+        // NPE is thrown when array is null
+        Preconditions.checkFromIndexSize(offset, len, array.length, AIOOBE_SUPPLIER);
+    }
+
     private static void swap(byte[] arr, int i, int j) {
         byte tmp = arr[i];
         arr[i] = arr[j];
@@ -48,4 +74,3 @@
         }
     }
 }
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/security/util/BiConsumer.java	Mon Jul 15 07:52:23 2019 +0100
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package sun.security.util;
+
+/**
+ * Represents an operation that accepts two input arguments and returns no
+ * result.  This is the two-arity specialization of {@link Consumer}.
+ * Unlike most other functional interfaces, {@code BiConsumer} is expected
+ * to operate via side-effects.
+ *
+ * @param <T> the type of the first argument to the operation
+ * @param <U> the type of the second argument to the operation
+ *
+ * @see Consumer
+ * @since 1.8
+ */
+public interface BiConsumer<T, U> {
+
+    /**
+     * Performs this operation on the given arguments.
+     *
+     * @param t the first input argument
+     * @param u the second input argument
+     */
+    void accept(T t, U u);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/security/util/BiFunction.java	Mon Jul 15 07:52:23 2019 +0100
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package sun.security.util;
+
+/**
+ * Represents a function that accepts two arguments and produces a result.
+ * This is the two-arity specialization of {@link Function}.
+ *
+ * @param <T> the type of the first argument to the function
+ * @param <U> the type of the second argument to the function
+ * @param <R> the type of the result of the function
+ *
+ * @see Function
+ * @since 1.8
+ */
+public interface BiFunction<T, U, R> {
+
+    /**
+     * Applies this function to the given arguments.
+     *
+     * @param t the first function argument
+     * @param u the second function argument
+     * @return the function result
+     */
+    R apply(T t, U u);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/security/util/IntSupplier.java	Mon Jul 15 07:52:23 2019 +0100
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package sun.security.util;
+
+/**
+ * Represents a supplier of {@code int}-valued results.  This is the
+ * {@code int}-producing primitive specialization of {@link Supplier}.
+ *
+ * <p>There is no requirement that a distinct result be returned each
+ * time the supplier is invoked.
+ *
+ * @see Supplier
+ * @since 1.8
+ */
+public interface IntSupplier {
+
+    /**
+     * Gets a result.
+     *
+     * @return a result
+     */
+    int getAsInt();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/sun/security/util/Preconditions.java	Mon Jul 15 07:52:23 2019 +0100
@@ -0,0 +1,343 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package sun.security.util;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Utility methods to check if state or arguments are correct.
+ *
+ */
+public class Preconditions {
+
+    /**
+     * Maps out-of-bounds values to a runtime exception.
+     *
+     * @param checkKind the kind of bounds check, whose name may correspond
+     *        to the name of one of the range check methods, checkIndex,
+     *        checkFromToIndex, checkFromIndexSize
+     * @param args the out-of-bounds arguments that failed the range check.
+     *        If the checkKind corresponds a the name of a range check method
+     *        then the bounds arguments are those that can be passed in order
+     *        to the method.
+     * @param oobef the exception formatter that when applied with a checkKind
+     *        and a list out-of-bounds arguments returns a runtime exception.
+     *        If {@code null} then, it is as if an exception formatter was
+     *        supplied that returns {@link IndexOutOfBoundsException} for any
+     *        given arguments.
+     * @return the runtime exception
+     */
+    private static RuntimeException outOfBounds(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobef,
+            String checkKind,
+            Integer... args) {
+        List<Integer> largs = Collections.unmodifiableList(Arrays.asList(args));
+        RuntimeException e = oobef == null
+                             ? null : oobef.apply(checkKind, largs);
+        return e == null
+               ? new IndexOutOfBoundsException(outOfBoundsMessage(checkKind, largs)) : e;
+    }
+
+    private static RuntimeException outOfBoundsCheckIndex(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
+            int index, int length) {
+        return outOfBounds(oobe, "checkIndex", index, length);
+    }
+
+    private static RuntimeException outOfBoundsCheckFromToIndex(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
+            int fromIndex, int toIndex, int length) {
+        return outOfBounds(oobe, "checkFromToIndex", fromIndex, toIndex, length);
+    }
+
+    private static RuntimeException outOfBoundsCheckFromIndexSize(
+            BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
+            int fromIndex, int size, int length) {
+        return outOfBounds(oobe, "checkFromIndexSize", fromIndex, size, length);
+    }
+
+    /**
+     * Returns an out-of-bounds exception formatter from an given exception
+     * factory.  The exception formatter is a function that formats an
+     * out-of-bounds message from its arguments and applies that message to the
+     * given exception factory to produce and relay an exception.
+     *
+     * <p>The exception formatter accepts two arguments: a {@code String}
+     * describing the out-of-bounds range check that failed, referred to as the
+     * <em>check kind</em>; and a {@code List<Integer>} containing the
+     * out-of-bound integer values that failed the check.  The list of
+     * out-of-bound values is not modified.
+     *
+     * <p>Three check kinds are supported {@code checkIndex},
+     * {@code checkFromToIndex} and {@code checkFromIndexSize} corresponding
+     * respectively to the specified application of an exception formatter as an
+     * argument to the out-of-bounds range check methods
+     * {@link #checkIndex(int, int, BiFunction) checkIndex},
+     * {@link #checkFromToIndex(int, int, int, BiFunction) checkFromToIndex}, and
+     * {@link #checkFromIndexSize(int, int, int, BiFunction) checkFromIndexSize}.
+     * Thus a supported check kind corresponds to a method name and the
+     * out-of-bound integer values correspond to method argument values, in
+     * order, preceding the exception formatter argument (similar in many
+     * respects to the form of arguments required for a reflective invocation of
+     * such a range check method).
+     *
+     * <p>Formatter arguments conforming to such supported check kinds will
+     * produce specific exception messages describing failed out-of-bounds
+     * checks.  Otherwise, more generic exception messages will be produced in
+     * any of the following cases: the check kind is supported but fewer
+     * or more out-of-bounds values are supplied, the check kind is not
+     * supported, the check kind is {@code null}, or the list of out-of-bound
+     * values is {@code null}.
+     *
+     * @apiNote
+     * This method produces an out-of-bounds exception formatter that can be
+     * passed as an argument to any of the supported out-of-bounds range check
+     * methods declared by {@code Objects}.  For example, a formatter producing
+     * an {@code ArrayIndexOutOfBoundsException} may be produced and stored on a
+     * {@code static final} field as follows:
+     * <pre>{@code
+     * static final
+     * BiFunction<String, List<Integer>, ArrayIndexOutOfBoundsException> AIOOBEF =
+     *     outOfBoundsExceptionFormatter(ArrayIndexOutOfBoundsException::new);
+     * }</pre>
+     * The formatter instance {@code AIOOBEF} may be passed as an argument to an
+     * out-of-bounds range check method, such as checking if an {@code index}
+     * is within the bounds of a {@code limit}:
+     * <pre>{@code
+     * checkIndex(index, limit, AIOOBEF);
+     * }</pre>
+     * If the bounds check fails then the range check method will throw an
+     * {@code ArrayIndexOutOfBoundsException} with an appropriate exception
+     * message that is a produced from {@code AIOOBEF} as follows:
+     * <pre>{@code
+     * AIOOBEF.apply("checkIndex", List.of(index, limit));
+     * }</pre>
+     *
+     * @param f the exception factory, that produces an exception from a message
+     *        where the message is produced and formatted by the returned
+     *        exception formatter.  If this factory is stateless and side-effect
+     *        free then so is the returned formatter.
+     *        Exceptions thrown by the factory are relayed to the caller
+     *        of the returned formatter.
+     * @param <X> the type of runtime exception to be returned by the given
+     *        exception factory and relayed by the exception formatter
+     * @return the out-of-bounds exception formatter
+     */
+    public static <X extends RuntimeException>
+    BiFunction<String, List<Integer>, X> outOfBoundsExceptionFormatter(final Function<String, X> f) {
+        // Use anonymous class to avoid bootstrap issues if this method is
+        // used early in startup
+        return new BiFunction<String, List<Integer>, X>() {
+            @Override
+            public X apply(String checkKind, List<Integer> args) {
+                return f.apply(outOfBoundsMessage(checkKind, args));
+            }
+        };
+    }
+
+    private static String outOfBoundsMessage(String checkKind, List<Integer> args) {
+        if (checkKind == null && args == null) {
+            return String.format("Range check failed");
+        } else if (checkKind == null) {
+            return String.format("Range check failed: %s", args);
+        } else if (args == null) {
+            return String.format("Range check failed: %s", checkKind);
+        }
+
+        int argSize = 0;
+        switch (checkKind) {
+            case "checkIndex":
+                argSize = 2;
+                break;
+            case "checkFromToIndex":
+            case "checkFromIndexSize":
+                argSize = 3;
+                break;
+            default:
+        }
+
+        // Switch to default if fewer or more arguments than required are supplied
+        switch ((args.size() != argSize) ? "" : checkKind) {
+            case "checkIndex":
+                return String.format("Index %d out-of-bounds for length %d",
+                                     args.get(0), args.get(1));
+            case "checkFromToIndex":
+                return String.format("Range [%d, %d) out-of-bounds for length %d",
+                                     args.get(0), args.get(1), args.get(2));
+            case "checkFromIndexSize":
+                return String.format("Range [%d, %<d + %d) out-of-bounds for length %d",
+                                     args.get(0), args.get(1), args.get(2));
+            default:
+                return String.format("Range check failed: %s %s", checkKind, args);
+        }
+    }
+
+    /**
+     * Checks if the {@code index} is within the bounds of the range from
+     * {@code 0} (inclusive) to {@code length} (exclusive).
+     *
+     * <p>The {@code index} is defined to be out-of-bounds if any of the
+     * following inequalities is true:
+     * <ul>
+     *  <li>{@code index < 0}</li>
+     *  <li>{@code index >= length}</li>
+     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
+     * </ul>
+     *
+     * <p>If the {@code index} is out-of-bounds, then a runtime exception is
+     * thrown that is the result of applying the following arguments to the
+     * exception formatter: the name of this method, {@code checkIndex};
+     * and an unmodifiable list integers whose values are, in order, the
+     * out-of-bounds arguments {@code index} and {@code length}.
+     *
+     * @param <X> the type of runtime exception to throw if the arguments are
+     *        out-of-bounds
+     * @param index the index
+     * @param length the upper-bound (exclusive) of the range
+     * @param oobef the exception formatter that when applied with this
+     *        method name and out-of-bounds arguments returns a runtime
+     *        exception.  If {@code null} or returns {@code null} then, it is as
+     *        if an exception formatter produced from an invocation of
+     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
+     *        instead (though it may be more efficient).
+     *        Exceptions thrown by the formatter are relayed to the caller.
+     * @return {@code index} if it is within bounds of the range
+     * @throws X if the {@code index} is out-of-bounds and the exception
+     *         formatter is non-{@code null}
+     * @throws IndexOutOfBoundsException if the {@code index} is out-of-bounds
+     *         and the exception formatter is {@code null}
+     * @since 9
+     *
+     * @implNote
+     * This method is made intrinsic in optimizing compilers to guide them to
+     * perform unsigned comparisons of the index and length when it is known the
+     * length is a non-negative value (such as that of an array length or from
+     * the upper bound of a loop)
+    */
+    public static <X extends RuntimeException>
+    int checkIndex(int index, int length,
+                   BiFunction<String, List<Integer>, X> oobef) {
+        if (index < 0 || index >= length)
+            throw outOfBoundsCheckIndex(oobef, index, length);
+        return index;
+    }
+
+    /**
+     * Checks if the sub-range from {@code fromIndex} (inclusive) to
+     * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
+     * (inclusive) to {@code length} (exclusive).
+     *
+     * <p>The sub-range is defined to be out-of-bounds if any of the following
+     * inequalities is true:
+     * <ul>
+     *  <li>{@code fromIndex < 0}</li>
+     *  <li>{@code fromIndex > toIndex}</li>
+     *  <li>{@code toIndex > length}</li>
+     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
+     * </ul>
+     *
+     * <p>If the sub-range  is out-of-bounds, then a runtime exception is
+     * thrown that is the result of applying the following arguments to the
+     * exception formatter: the name of this method, {@code checkFromToIndex};
+     * and an unmodifiable list integers whose values are, in order, the
+     * out-of-bounds arguments {@code fromIndex}, {@code toIndex}, and {@code length}.
+     *
+     * @param <X> the type of runtime exception to throw if the arguments are
+     *        out-of-bounds
+     * @param fromIndex the lower-bound (inclusive) of the sub-range
+     * @param toIndex the upper-bound (exclusive) of the sub-range
+     * @param length the upper-bound (exclusive) the range
+     * @param oobef the exception formatter that when applied with this
+     *        method name and out-of-bounds arguments returns a runtime
+     *        exception.  If {@code null} or returns {@code null} then, it is as
+     *        if an exception formatter produced from an invocation of
+     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
+     *        instead (though it may be more efficient).
+     *        Exceptions thrown by the formatter are relayed to the caller.
+     * @return {@code fromIndex} if the sub-range within bounds of the range
+     * @throws X if the sub-range is out-of-bounds and the exception factory
+     *         function is non-{@code null}
+     * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
+     *         the exception factory function is {@code null}
+     * @since 9
+     */
+    public static <X extends RuntimeException>
+    int checkFromToIndex(int fromIndex, int toIndex, int length,
+                         BiFunction<String, List<Integer>, X> oobef) {
+        if (fromIndex < 0 || fromIndex > toIndex || toIndex > length)
+            throw outOfBoundsCheckFromToIndex(oobef, fromIndex, toIndex, length);
+        return fromIndex;
+    }
+
+    /**
+     * Checks if the sub-range from {@code fromIndex} (inclusive) to
+     * {@code fromIndex + size} (exclusive) is within the bounds of range from
+     * {@code 0} (inclusive) to {@code length} (exclusive).
+     *
+     * <p>The sub-range is defined to be out-of-bounds if any of the following
+     * inequalities is true:
+     * <ul>
+     *  <li>{@code fromIndex < 0}</li>
+     *  <li>{@code size < 0}</li>
+     *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
+     *  <li>{@code length < 0}, which is implied from the former inequalities</li>
+     * </ul>
+     *
+     * <p>If the sub-range  is out-of-bounds, then a runtime exception is
+     * thrown that is the result of applying the following arguments to the
+     * exception formatter: the name of this method, {@code checkFromIndexSize};
+     * and an unmodifiable list integers whose values are, in order, the
+     * out-of-bounds arguments {@code fromIndex}, {@code size}, and
+     * {@code length}.
+     *
+     * @param <X> the type of runtime exception to throw if the arguments are
+     *        out-of-bounds
+     * @param fromIndex the lower-bound (inclusive) of the sub-interval
+     * @param size the size of the sub-range
+     * @param length the upper-bound (exclusive) of the range
+     * @param oobef the exception formatter that when applied with this
+     *        method name and out-of-bounds arguments returns a runtime
+     *        exception.  If {@code null} or returns {@code null} then, it is as
+     *        if an exception formatter produced from an invocation of
+     *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
+     *        instead (though it may be more efficient).
+     *        Exceptions thrown by the formatter are relayed to the caller.
+     * @return {@code fromIndex} if the sub-range within bounds of the range
+     * @throws X if the sub-range is out-of-bounds and the exception factory
+     *         function is non-{@code null}
+     * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
+     *         the exception factory function is {@code null}
+     * @since 9
+     */
+    public static <X extends RuntimeException>
+    int checkFromIndexSize(int fromIndex, int size, int length,
+                           BiFunction<String, List<Integer>, X> oobef) {
+        if ((length | fromIndex | size) < 0 || size > length - fromIndex)
+            throw outOfBoundsCheckFromIndexSize(oobef, fromIndex, size, length);
+        return fromIndex;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/util/Objects/CheckIndex.java	Mon Jul 15 07:52:23 2019 +0100
@@ -0,0 +1,408 @@
+/*
+ * Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @summary Objects.checkIndex/jdk.internal.util.Preconditions.checkIndex tests
+ * @run testng CheckIndex
+ * @bug 8135248 8142493 8155794
+ */
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+
+import sun.security.util.BiConsumer;
+import sun.security.util.BiFunction;
+import sun.security.util.Function;
+import sun.security.util.IntSupplier;
+import sun.security.util.Preconditions;
+
+import static org.testng.Assert.*;
+
+public class CheckIndex {
+
+    private static final Function<String, IndexOutOfBoundsException> ioobeGenerator =
+        new Function<String, IndexOutOfBoundsException>() {
+           @Override
+           public IndexOutOfBoundsException apply(String x) {
+               return new IndexOutOfBoundsException(x);
+           }
+        };
+
+    private static final Function<String, StringIndexOutOfBoundsException> sioobeGenerator =
+        new Function<String, StringIndexOutOfBoundsException>() {
+           @Override
+           public StringIndexOutOfBoundsException apply(String x) {
+               return new StringIndexOutOfBoundsException(x);
+           }
+        };
+
+    private static final Function<String, ArrayIndexOutOfBoundsException> aioobeGenerator =
+        new Function<String, ArrayIndexOutOfBoundsException>() {
+           @Override
+           public ArrayIndexOutOfBoundsException apply(String x) {
+               return new ArrayIndexOutOfBoundsException(x);
+           }
+        };
+
+    static class AssertingOutOfBoundsException extends RuntimeException {
+        public AssertingOutOfBoundsException(String message) {
+            super(message);
+        }
+    }
+
+    static BiFunction<String, List<Integer>, AssertingOutOfBoundsException> assertingOutOfBounds(
+            final String message, final String expCheckKind, final Integer... expArgs) {
+        return new BiFunction<String, List<Integer>, AssertingOutOfBoundsException>() {
+            @Override
+            public AssertingOutOfBoundsException apply(String checkKind, List<Integer> args) {
+                assertEquals(checkKind, expCheckKind);
+                assertEquals(args, Collections.unmodifiableList(Arrays.asList(expArgs)));
+                try {
+                    args.clear();
+                    fail("Out of bounds List<Integer> argument should be unmodifiable");
+                } catch (Exception e)  {
+                }
+                return new AssertingOutOfBoundsException(message);
+            }
+        };
+    }
+
+    static BiFunction<String, List<Integer>, AssertingOutOfBoundsException> assertingOutOfBoundsReturnNull(
+            final String expCheckKind, final Integer... expArgs) {
+        return new BiFunction<String, List<Integer>, AssertingOutOfBoundsException>() {
+            @Override
+            public AssertingOutOfBoundsException apply(String checkKind, List<Integer> args) {
+                assertEquals(checkKind, expCheckKind);
+                assertEquals(args, Collections.unmodifiableList(Arrays.asList(expArgs)));
+                return null;
+            }
+        };
+    }
+
+    static final int[] VALUES = {0, 1, Integer.MAX_VALUE - 1, Integer.MAX_VALUE, -1, Integer.MIN_VALUE + 1, Integer.MIN_VALUE};
+
+    @DataProvider
+    static Object[][] checkIndexProvider() {
+        List<Object[]> l = new ArrayList<>();
+        for (int index : VALUES) {
+            for (int length : VALUES) {
+                boolean withinBounds = index >= 0 &&
+                                       length >= 0 &&
+                                       index < length;
+                l.add(new Object[]{index, length, withinBounds});
+            }
+        }
+        return l.toArray(new Object[0][0]);
+    }
+
+    interface X {
+        int apply(int a, int b, int c);
+    }
+
+    @Test(dataProvider = "checkIndexProvider")
+    public void testCheckIndex(final int index, final int length, final boolean withinBounds) {
+        List<Integer> list = Collections.unmodifiableList(Arrays.asList(new Integer[] { index, length }));
+        final String expectedMessage = withinBounds
+                                       ? null
+                                       : Preconditions.outOfBoundsExceptionFormatter(ioobeGenerator).
+                apply("checkIndex", list).getMessage();
+
+        BiConsumer<Class<? extends RuntimeException>, IntSupplier> checker =
+            new BiConsumer<Class<? extends RuntimeException>, IntSupplier>() {
+            @Override
+            public void accept(Class<? extends RuntimeException> ec, IntSupplier s) {
+                try {
+                    int rIndex = s.getAsInt();
+                    if (!withinBounds)
+                        fail(String.format(
+                            "Index %d is out of bounds of [0, %d), but was reported to be within bounds", index, length));
+                    assertEquals(rIndex, index);
+                }
+                catch (RuntimeException e) {
+                    assertTrue(ec.isInstance(e));
+                    if (withinBounds)
+                        fail(String.format(
+                            "Index %d is within bounds of [0, %d), but was reported to be out of bounds", index, length));
+                    else
+                        assertEquals(e.getMessage(), expectedMessage);
+                }
+            }
+        };
+
+        checker.accept(AssertingOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkIndex(index, length,
+                                                assertingOutOfBounds(expectedMessage, "checkIndex", index, length));
+            }
+        });
+        checker.accept(IndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkIndex(index, length,
+                                                assertingOutOfBoundsReturnNull("checkIndex", index, length));
+            }
+        });
+        checker.accept(IndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkIndex(index, length, null);
+            }
+        });
+        checker.accept(ArrayIndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkIndex(index, length,
+                                                Preconditions.outOfBoundsExceptionFormatter(aioobeGenerator));
+            }
+        });
+        checker.accept(StringIndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkIndex(index, length,
+                                                Preconditions.outOfBoundsExceptionFormatter(sioobeGenerator));
+            }
+        });
+    }
+
+
+    @DataProvider
+    static Object[][] checkFromToIndexProvider() {
+        List<Object[]> l = new ArrayList<>();
+        for (int fromIndex : VALUES) {
+            for (int toIndex : VALUES) {
+                for (int length : VALUES) {
+                    boolean withinBounds = fromIndex >= 0 &&
+                                           toIndex >= 0 &&
+                                           length >= 0 &&
+                                           fromIndex <= toIndex &&
+                                           toIndex <= length;
+                    l.add(new Object[]{fromIndex, toIndex, length, withinBounds});
+                }
+            }
+        }
+        return l.toArray(new Object[0][0]);
+    }
+
+    @Test(dataProvider = "checkFromToIndexProvider")
+    public void testCheckFromToIndex(final int fromIndex, final int toIndex,
+                                     final int length, final boolean withinBounds) {
+        List<Integer> list = Collections.unmodifiableList(Arrays.asList(new Integer[] { fromIndex, toIndex, length }));
+        final String expectedMessage = withinBounds
+                                       ? null
+                                       : Preconditions.outOfBoundsExceptionFormatter(ioobeGenerator).
+                apply("checkFromToIndex", list).getMessage();
+
+        BiConsumer<Class<? extends RuntimeException>, IntSupplier> check =
+            new BiConsumer<Class<? extends RuntimeException>, IntSupplier>() {
+            @Override
+            public void accept(Class<? extends RuntimeException> ec, IntSupplier s) {
+                try {
+                    int rIndex = s.getAsInt();
+                    if (!withinBounds)
+                        fail(String.format(
+                            "Range [%d, %d) is out of bounds of [0, %d), but was reported to be withing bounds", fromIndex, toIndex, length));
+                    assertEquals(rIndex, fromIndex);
+                }
+                catch (RuntimeException e) {
+                    assertTrue(ec.isInstance(e));
+                    if (withinBounds)
+                        fail(String.format(
+                            "Range [%d, %d) is within bounds of [0, %d), but was reported to be out of bounds", fromIndex, toIndex, length));
+                    else
+                        assertEquals(e.getMessage(), expectedMessage);
+                }
+            }
+        };
+
+        check.accept(AssertingOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromToIndex(fromIndex, toIndex, length,
+                                                      assertingOutOfBounds(expectedMessage, "checkFromToIndex", fromIndex, toIndex, length));
+            }
+        });
+        check.accept(IndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return  Preconditions.checkFromToIndex(fromIndex, toIndex, length,
+                                                       assertingOutOfBoundsReturnNull("checkFromToIndex", fromIndex, toIndex, length));
+            }
+        });
+        check.accept(IndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
+            }
+        });
+        check.accept(ArrayIndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromToIndex(fromIndex, toIndex, length,
+                                                      Preconditions.outOfBoundsExceptionFormatter(aioobeGenerator));
+            }
+        });
+        check.accept(StringIndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromToIndex(fromIndex, toIndex, length,
+                                                      Preconditions.outOfBoundsExceptionFormatter(sioobeGenerator));
+            }
+        });
+    }
+
+
+    @DataProvider
+    static Object[][] checkFromIndexSizeProvider() {
+        List<Object[]> l = new ArrayList<>();
+        for (int fromIndex : VALUES) {
+            for (int size : VALUES) {
+                for (int length : VALUES) {
+                    // Explicitly convert to long
+                    long lFromIndex = fromIndex;
+                    long lSize = size;
+                    long lLength = length;
+                    // Avoid overflow
+                    long lToIndex = lFromIndex + lSize;
+
+                    boolean withinBounds = lFromIndex >= 0L &&
+                                           lSize >= 0L &&
+                                           lLength >= 0L &&
+                                           lFromIndex <= lToIndex &&
+                                           lToIndex <= lLength;
+                    l.add(new Object[]{fromIndex, size, length, withinBounds});
+                }
+            }
+        }
+        return l.toArray(new Object[0][0]);
+    }
+
+    @Test(dataProvider = "checkFromIndexSizeProvider")
+    public void testCheckFromIndexSize(final int fromIndex, final int size,
+                                       final int length, final boolean withinBounds) {
+        List<Integer> list = Collections.unmodifiableList(Arrays.asList(new Integer[] { fromIndex, size, length }));
+        final String expectedMessage = withinBounds
+                                       ? null
+                                       : Preconditions.outOfBoundsExceptionFormatter(ioobeGenerator).
+                apply("checkFromIndexSize", list).getMessage();
+
+        BiConsumer<Class<? extends RuntimeException>, IntSupplier> check =
+            new BiConsumer<Class<? extends RuntimeException>, IntSupplier>() {
+                @Override
+                public void accept(Class<? extends RuntimeException> ec, IntSupplier s) {
+                    try {
+                        int rIndex = s.getAsInt();
+                        if (!withinBounds)
+                            fail(String.format(
+                                "Range [%d, %d + %d) is out of bounds of [0, %d), but was reported to be withing bounds", fromIndex, fromIndex, size, length));
+                        assertEquals(rIndex, fromIndex);
+                    }
+                    catch (RuntimeException e) {
+                        assertTrue(ec.isInstance(e));
+                        if (withinBounds)
+                            fail(String.format(
+                                "Range [%d, %d + %d) is within bounds of [0, %d), but was reported to be out of bounds", fromIndex, fromIndex, size, length));
+                else
+                    assertEquals(e.getMessage(), expectedMessage);
+                    }
+                }
+            };
+
+        check.accept(AssertingOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromIndexSize(fromIndex, size, length,
+                                                        assertingOutOfBounds(expectedMessage, "checkFromIndexSize", fromIndex, size, length));
+            }
+        });
+        check.accept(IndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromIndexSize(fromIndex, size, length,
+                                                        assertingOutOfBoundsReturnNull("checkFromIndexSize", fromIndex, size, length));
+            }
+        });
+        check.accept(IndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
+            }
+        });
+        check.accept(ArrayIndexOutOfBoundsException.class, new IntSupplier() {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromIndexSize(fromIndex, size, length,
+                                                        Preconditions.outOfBoundsExceptionFormatter(aioobeGenerator));
+            }
+        });
+        check.accept(StringIndexOutOfBoundsException.class, new IntSupplier () {
+            @Override
+            public int getAsInt() {
+                return Preconditions.checkFromIndexSize(fromIndex, size, length,
+                                                        Preconditions.outOfBoundsExceptionFormatter(sioobeGenerator));
+            }
+        });
+    }
+
+    @Test
+    public void uniqueMessagesForCheckKinds() {
+        BiFunction<String, List<Integer>, IndexOutOfBoundsException> f =
+                Preconditions.outOfBoundsExceptionFormatter(ioobeGenerator);
+
+        List<String> messages = new ArrayList<>();
+        List<Integer> arg1 = Collections.unmodifiableList(Arrays.asList(new Integer[] { -1 }));
+        List<Integer> arg2 = Collections.unmodifiableList(Arrays.asList(new Integer[] { -1, 0 }));
+        List<Integer> arg3 = Collections.unmodifiableList(Arrays.asList(new Integer[] { -1, 0, 0 }));
+        List<Integer> arg4 = Collections.unmodifiableList(Arrays.asList(new Integer[] { -1, 0, 0, 0 }));
+        // Exact arguments
+        messages.add(f.apply("checkIndex", arg2).getMessage());
+        messages.add(f.apply("checkFromToIndex", arg3).getMessage());
+        messages.add(f.apply("checkFromIndexSize", arg3).getMessage());
+        // Unknown check kind
+        messages.add(f.apply("checkUnknown", arg3).getMessage());
+        // Known check kind with more arguments
+        messages.add(f.apply("checkIndex", arg3).getMessage());
+        messages.add(f.apply("checkFromToIndex", arg4).getMessage());
+        messages.add(f.apply("checkFromIndexSize", arg4).getMessage());
+        // Known check kind with fewer arguments
+        messages.add(f.apply("checkIndex", arg1).getMessage());
+        messages.add(f.apply("checkFromToIndex", arg2).getMessage());
+        messages.add(f.apply("checkFromIndexSize", arg2).getMessage());
+        // Null arguments
+        messages.add(f.apply(null, null).getMessage());
+        messages.add(f.apply("checkNullArguments", null).getMessage());
+        messages.add(f.apply(null, arg1).getMessage());
+
+        Set<String> distinct = new HashSet<>(messages);
+        assertEquals(messages.size(), distinct.size());
+    }
+}
--- a/test/sun/security/util/math/TestIntegerModuloP.java	Thu Jul 04 18:20:08 2019 +0100
+++ b/test/sun/security/util/math/TestIntegerModuloP.java	Mon Jul 15 07:52:23 2019 +0100
@@ -37,6 +37,7 @@
  * @run main TestIntegerModuloP sun.security.util.math.intpoly.P521OrderField 66 10
  */
 
+import sun.security.util.BiFunction;
 import sun.security.util.math.*;
 import sun.security.util.math.intpoly.*;
 
@@ -51,9 +52,6 @@
     // The test has a list of functions, and it selects randomly from that list
 
     // The function types
-    interface BiFunction <T, U, V> {
-        V apply(T t, U u);
-    }
     interface ElemFunction extends BiFunction
         <MutableIntegerModuloP, IntegerModuloP, IntegerModuloP> { }
     interface ElemArrayFunction extends BiFunction