8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior
authormchung
Fri, 17 Nov 2017 08:12:02 -0600
changeset 47856 76519338df34
parent 47855 72b6d674bde2
child 47857 13415772f06a
8157246: MHs.arrayLength, arrayElementGetter/Setter, arrayConstructor need to specify invocation-time behavior Reviewed-by: psandoz, rriggs
src/java.base/share/classes/java/lang/invoke/MethodHandle.java
src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java
src/java.base/share/classes/java/lang/invoke/MethodHandles.java
test/jdk/java/lang/invoke/ArrayConstructorTest.java
test/jdk/java/lang/invoke/ArrayLengthTest.java
test/jdk/java/lang/invoke/InvokeMethodHandleWithBadArgument.java
test/jdk/java/lang/invoke/JavaDocExamplesTest.java
test/jdk/java/lang/invoke/SpreadCollectTest.java
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandle.java	Fri Nov 17 18:43:27 2017 +0530
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandle.java	Fri Nov 17 08:12:02 2017 -0600
@@ -886,9 +886,13 @@
      * to the target method handle.
      * (The array may also be null when zero elements are required.)
      * <p>
-     * If, when the adapter is called, the supplied array argument does
-     * not have the correct number of elements, the adapter will throw
-     * an {@link IllegalArgumentException} instead of invoking the target.
+     * When the adapter is called, the length of the supplied {@code array}
+     * argument is queried as if by {@code array.length} or {@code arraylength}
+     * bytecode. If the adapter accepts a zero-length trailing array argument,
+     * the supplied {@code array} argument can either be a zero-length array or
+     * {@code null}; otherwise, the adapter will throw a {@code NullPointerException}
+     * if the array is {@code null} and throw an {@link IllegalArgumentException}
+     * if the array does not have the correct number of elements.
      * <p>
      * Here are some simple examples of array-spreading method handles:
      * <blockquote><pre>{@code
@@ -902,7 +906,7 @@
 assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
 // try to spread from anything but a 2-array:
 for (int n = 0; n <= 10; n++) {
-  Object[] badArityArgs = (n == 2 ? null : new Object[n]);
+  Object[] badArityArgs = (n == 2 ? new Object[0] : new Object[n]);
   try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
   catch (IllegalArgumentException ex) { } // OK
 }
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Fri Nov 17 18:43:27 2017 +0530
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Fri Nov 17 08:12:02 2017 -0600
@@ -662,8 +662,10 @@
     }
 
     static void checkSpreadArgument(Object av, int n) {
-        if (av == null) {
-            if (n == 0)  return;
+        if (av == null && n == 0) {
+            return;
+        } else if (av == null) {
+            throw new NullPointerException("null array reference");
         } else if (av instanceof Object[]) {
             int len = ((Object[])av).length;
             if (len == n)  return;
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Fri Nov 17 18:43:27 2017 +0530
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Fri Nov 17 08:12:02 2017 -0600
@@ -2514,14 +2514,20 @@
     }
 
     /**
-     * Produces a method handle constructing arrays of a desired type.
+     * Produces a method handle constructing arrays of a desired type,
+     * as if by the {@code anewarray} bytecode.
      * The return type of the method handle will be the array type.
      * The type of its sole argument will be {@code int}, which specifies the size of the array.
+     *
+     * <p> If the returned method handle is invoked with a negative
+     * array size, a {@code NegativeArraySizeException} will be thrown.
+     *
      * @param arrayClass an array type
      * @return a method handle which can create arrays of the given type
      * @throws NullPointerException if the argument is {@code null}
      * @throws IllegalArgumentException if {@code arrayClass} is not an array type
      * @see java.lang.reflect.Array#newInstance(Class, int)
+     * @jvms 6.5 {@code anewarray} Instruction
      * @since 9
      */
     public static
@@ -2535,13 +2541,19 @@
     }
 
     /**
-     * Produces a method handle returning the length of an array.
+     * Produces a method handle returning the length of an array,
+     * as if by the {@code arraylength} bytecode.
      * The type of the method handle will have {@code int} as return type,
      * and its sole argument will be the array type.
+     *
+     * <p> If the returned method handle is invoked with a {@code null}
+     * array reference, a {@code NullPointerException} will be thrown.
+     *
      * @param arrayClass an array type
      * @return a method handle which can retrieve the length of an array of the given array type
      * @throws NullPointerException if the argument is {@code null}
      * @throws IllegalArgumentException if arrayClass is not an array type
+     * @jvms 6.5 {@code arraylength} Instruction
      * @since 9
      */
     public static
@@ -2550,14 +2562,24 @@
     }
 
     /**
-     * Produces a method handle giving read access to elements of an array.
+     * Produces a method handle giving read access to elements of an array,
+     * as if by the {@code aaload} bytecode.
      * The type of the method handle will have a return type of the array's
      * element type.  Its first argument will be the array type,
      * and the second will be {@code int}.
+     *
+     * <p> When the returned method handle is invoked,
+     * the array reference and array index are checked.
+     * A {@code NullPointerException} will be thrown if the array reference
+     * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
+     * thrown if the index is negative or if it is greater than or equal to
+     * the length of the array.
+     *
      * @param arrayClass an array type
      * @return a method handle which can load values from the given array type
      * @throws NullPointerException if the argument is null
      * @throws  IllegalArgumentException if arrayClass is not an array type
+     * @jvms 6.5 {@code aaload} Instruction
      */
     public static
     MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException {
@@ -2565,14 +2587,24 @@
     }
 
     /**
-     * Produces a method handle giving write access to elements of an array.
+     * Produces a method handle giving write access to elements of an array,
+     * as if by the {@code astore} bytecode.
      * The type of the method handle will have a void return type.
      * Its last argument will be the array's element type.
      * The first and second arguments will be the array type and int.
+     *
+     * <p> When the returned method handle is invoked,
+     * the array reference and array index are checked.
+     * A {@code NullPointerException} will be thrown if the array reference
+     * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
+     * thrown if the index is negative or if it is greater than or equal to
+     * the length of the array.
+     *
      * @param arrayClass the class of an array
      * @return a method handle which can store values into the array type
      * @throws NullPointerException if the argument is null
      * @throws IllegalArgumentException if arrayClass is not an array type
+     * @jvms 6.5 {@code aastore} Instruction
      */
     public static
     MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException {
@@ -2603,6 +2635,14 @@
      * and atomic update access modes compare values using their bitwise
      * representation (see {@link Float#floatToRawIntBits} and
      * {@link Double#doubleToRawLongBits}, respectively).
+     *
+     * <p> When the returned {@code VarHandle} is invoked,
+     * the array reference and array index are checked.
+     * A {@code NullPointerException} will be thrown if the array reference
+     * is {@code null} and an {@code ArrayIndexOutOfBoundsException} will be
+     * thrown if the index is negative or if it is greater than or equal to
+     * the length of the array.
+     *
      * @apiNote
      * Bitwise comparison of {@code float} values or {@code double} values,
      * as performed by the numeric and atomic update access modes, differ
--- a/test/jdk/java/lang/invoke/ArrayConstructorTest.java	Fri Nov 17 18:43:27 2017 +0530
+++ b/test/jdk/java/lang/invoke/ArrayConstructorTest.java	Fri Nov 17 08:12:02 2017 -0600
@@ -88,4 +88,11 @@
         assertEquals(17, a.length);
     }
 
+    @Test(expectedExceptions = {NegativeArraySizeException.class})
+    public static void testArrayConstructorNegativeIndex() throws Throwable {
+        MethodHandle h = MethodHandles.arrayConstructor(String[].class);
+        assertEquals(methodType(String[].class, int.class), h.type());
+        h.invoke(-1); // throws exception
+    }
+
 }
--- a/test/jdk/java/lang/invoke/ArrayLengthTest.java	Fri Nov 17 18:43:27 2017 +0530
+++ b/test/jdk/java/lang/invoke/ArrayLengthTest.java	Fri Nov 17 08:12:02 2017 -0600
@@ -78,4 +78,9 @@
         MethodHandles.arrayLength(null);
     }
 
+    @Test(expectedExceptions = NullPointerException.class)
+    public void testNullReference() throws Throwable {
+        MethodHandle arrayLength = MethodHandles.arrayLength(String[].class);
+        int len = (int)arrayLength.invokeExact((String[])null);
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/java/lang/invoke/InvokeMethodHandleWithBadArgument.java	Fri Nov 17 08:12:02 2017 -0600
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+/*
+ * @test
+ * @bug 8157246
+ * @summary Tests invocation of MethodHandle with invalid leading argument
+ * @run testng/othervm test.java.lang.invoke.InvokeMethodHandleWithBadArgument
+ */
+
+package test.java.lang.invoke;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.lang.invoke.VarHandle;
+
+import static java.lang.invoke.MethodType.methodType;
+
+import static org.testng.AssertJUnit.*;
+
+import org.testng.annotations.*;
+
+/**
+ * Tests invocation of MethodHandle with invalid leading argument such as
+ * MethodHandle, VarHandle, and array object
+ */
+public class InvokeMethodHandleWithBadArgument {
+    // ---- null array reference ----
+
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testAsSpreaderPosInvokeWithNull() throws Throwable {
+        MethodHandle spreader = MH_spread.asSpreader(1, int[].class, 3);
+        spreader.invoke("A", null, "B");
+    }
+
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testAsSpreaderInvokeWithNull() throws Throwable {
+        MethodHandle spreader = MH_String_equals.asSpreader(String[].class, 2);
+        assert ((boolean) spreader.invokeExact(new String[]{"me", "me"}));
+        boolean eq = (boolean) spreader.invokeExact((String[]) null);
+    }
+
+    // ---- incorrect array element count ----
+    @Test(expectedExceptions = {IllegalArgumentException.class})
+    public static void testAsSpreaderPosInvokeWithBadElementCount() throws Throwable {
+        MethodHandle spreader = MH_spread.asSpreader(1, int[].class, 3);
+        spreader.invoke("A", new int[]{1, 2}, "B");
+    }
+
+    @Test(expectedExceptions = {IllegalArgumentException.class})
+    public static void testAsSpreaderInvokeWithBadElementCount() throws Throwable {
+        MethodHandle spreader = MH_String_equals.asSpreader(String[].class, 2);
+        assert (!(boolean) spreader.invokeExact(new String[]{"me", "thee"}));
+        boolean eq = (boolean) spreader.invokeExact(new String[0]);
+    }
+
+    // ---- spread no argument ----
+    @Test
+    public static void testAsSpreaderPosInvokeWithZeroLength() throws Throwable {
+        MethodHandle spreader = MH_spread.asSpreader(1, int[].class, 0);
+        assert("A123B".equals(spreader.invoke("A", (int[])null, 1, 2, 3, "B")));
+    }
+
+    @Test
+    public static void testAsSpreaderInvokeWithZeroLength() throws Throwable {
+        MethodHandle spreader = MH_String_equals.asSpreader(String[].class, 0);
+        assert ((boolean) spreader.invokeExact("me", (Object)"me", new String[0]));
+        boolean eq = (boolean) spreader.invokeExact("me", (Object)"me", (String[]) null);
+    }
+
+    // ---- invokers with null method/var handle argument ----
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testInvokerWithNull() throws Throwable {
+        MethodType type = methodType(int.class, int.class, int.class);
+        MethodHandle invoker = MethodHandles.invoker(type);
+        assert((int) invoker.invoke(MH_add, 1, 2) == 3);
+        int sum = (int)invoker.invoke((MethodHandle)null, 1, 2);
+    }
+
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testExactInvokerWithNull() throws Throwable {
+        MethodType type = methodType(int.class, int.class, int.class);
+        MethodHandle invoker = MethodHandles.exactInvoker(type);
+        assert((int) invoker.invoke(MH_add, 1, 2) == 3);
+        int sum = (int)invoker.invokeExact((MethodHandle)null, 1, 2);
+    }
+
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testSpreadInvokerWithNull() throws Throwable {
+        MethodType type = methodType(boolean.class, String.class, String.class);
+        MethodHandle invoker = MethodHandles.spreadInvoker(type, 0);
+        assert ((boolean) invoker.invoke(MH_String_equals, new String[]{"me", "me"}));
+        boolean eq = (boolean) invoker.invoke((MethodHandle)null, new String[]{"me", "me"});
+    }
+
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testVarHandleInvokerWithNull() throws Throwable {
+        VarHandle.AccessMode am = VarHandle.AccessMode.GET;
+        MethodHandle invoker = MethodHandles.varHandleInvoker(am, VH_array.accessModeType(am));
+        assert ((int) invoker.invoke(VH_array, array, 3) == 3);
+        int value = (int)invoker.invoke((VarHandle)null, array, 3);
+    }
+
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testVarHandleExactInvokerWithNull() throws Throwable {
+        VarHandle.AccessMode am = VarHandle.AccessMode.GET;
+        MethodHandle invoker = MethodHandles.varHandleExactInvoker(am, VH_array.accessModeType(am));
+        assert ((int) invoker.invoke(VH_array, array, 3) == 3);
+        int value = (int)invoker.invokeExact((VarHandle)null, array, 3);
+    }
+
+    static final Lookup LOOKUP = MethodHandles.lookup();
+    static final MethodHandle MH_add;
+    static final MethodHandle MH_spread;
+    static final MethodHandle MH_String_equals;
+    static final VarHandle VH_array;
+
+    static final int[] array = new int[] { 0, 1, 2, 3, 4, 5};
+    static {
+        try {
+            Class<?> arrayClass = Class.forName("[I");
+            VH_array = MethodHandles.arrayElementVarHandle(arrayClass);
+            MH_add = LOOKUP.findStatic(InvokeMethodHandleWithBadArgument.class, "add",
+                methodType(int.class, int.class, int.class));
+            MH_spread = LOOKUP.findStatic(InvokeMethodHandleWithBadArgument.class, "spread",
+                methodType(String.class, String.class, int.class, int.class, int.class, String.class));
+            MH_String_equals = LOOKUP.findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
+        } catch (Exception e) {
+            throw new ExceptionInInitializerError(e);
+        }
+    }
+
+    static String spread(String s1, int i1, int i2, int i3, String s2) {
+        return s1 + i1 + i2 + i3 + s2;
+    }
+
+    static int add(int x, int y) {
+        return x+y;
+    }
+}
--- a/test/jdk/java/lang/invoke/JavaDocExamplesTest.java	Fri Nov 17 18:43:27 2017 +0530
+++ b/test/jdk/java/lang/invoke/JavaDocExamplesTest.java	Fri Nov 17 08:12:02 2017 -0600
@@ -415,7 +415,7 @@
 assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
 // try to spread from anything but a 2-array:
 for (int n = 0; n <= 10; n++) {
-  Object[] badArityArgs = (n == 2 ? null : new Object[n]);
+  Object[] badArityArgs = (n == 2 ? new Object[0] : new Object[n]);
   try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
   catch (IllegalArgumentException ex) { } // OK
 }
--- a/test/jdk/java/lang/invoke/SpreadCollectTest.java	Fri Nov 17 18:43:27 2017 +0530
+++ b/test/jdk/java/lang/invoke/SpreadCollectTest.java	Fri Nov 17 08:12:02 2017 -0600
@@ -94,6 +94,21 @@
         MethodHandle s = h.asSpreader(String[].class, 1);
     }
 
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testAsSpreaderNullArrayType() {
+        SpreadCollect.MH_forSpreading.asSpreader(null, 0);
+    }
+
+    @Test(expectedExceptions = {NullPointerException.class})
+    public static void testAsSpreaderNullArrayNonZeroLength() {
+        SpreadCollect.MH_forSpreading.asSpreader(null, 1);
+    }
+
+    @Test(expectedExceptions = {IllegalArgumentException.class})
+    public static void testAsSpreaderTooManyParams() throws Throwable {
+        SpreadCollect.MH_forSpreading.asSpreader(1, int[].class, 6);
+    }
+
     @Test
     public static void testAsCollector() throws Throwable {
         MethodHandle collector = SpreadCollect.MH_forCollecting.asCollector(1, int[].class, 1);