1 /*
   2  * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /* @test
  25  * @summary unit tests for method handles which permute their arguments
  26  * @library /lib/testlibrary/jsr292 /lib/testlibrary
  27  * @run testng/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-VerifyDependencies -ea -esa -DPermuteArgsTest.MAX_ARITY=8 test.java.lang.invoke.PermuteArgsTest
  28  */
  29 /* Examples of manual runs:
  30  * java -DPermuteArgsTest.{DRY_RUN=true,MAX_ARITY=253} test.java.lang.invoke.PermuteArgsTest
  31  * java -DPermuteArgsTest.{VERBOSE=true,MAX_ARITY=5} test.java.lang.invoke.PermuteArgsTest
  32  * java test.java.lang.invoke.PermuteArgsTest list3I[2,0,1] listJLJ[2,0,1]
  33  */
  34 
  35 package test.java.lang.invoke;
  36 
  37 import org.testng.*;
  38 import org.testng.annotations.*;
  39 
  40 import com.oracle.testlibrary.jsr292.CodeCacheOverflowProcessor;
  41 
  42 import java.util.*;
  43 import java.lang.reflect.*;
  44 
  45 import java.lang.invoke.*;
  46 import static java.lang.invoke.MethodHandles.*;
  47 import static java.lang.invoke.MethodType.*;
  48 
  49 public class PermuteArgsTest {
  50     private static final Class<?> CLASS = PermuteArgsTest.class;
  51     private static final int MAX_ARITY = Integer.getInteger(CLASS.getSimpleName()+".MAX_ARITY", 8);
  52     private static final boolean DRY_RUN = Boolean.getBoolean(CLASS.getSimpleName()+".DRY_RUN");
  53     private static final boolean VERBOSE = Boolean.getBoolean(CLASS.getSimpleName()+".VERBOSE") || DRY_RUN;
  54 
  55     static Object list2I(int x, int y) {
  56         return Arrays.asList(x, y);
  57     }
  58     static Object list3I(int x, int y, int z) {
  59         return Arrays.asList(x, y, z);
  60     }
  61     static Object list4I(int w, int x, int y, int z) {
  62         return Arrays.asList(w, x, y, z);
  63     }
  64     static Object list2J(long x, long y) {
  65         return Arrays.asList(x, y);
  66     }
  67     static Object list3J(long x, long y, long z) {
  68         return Arrays.asList(x, y, z);
  69     }
  70     static Object list4J(long w, long x, long y, long z) {
  71         return Arrays.asList(w, x, y, z);
  72     }
  73     static Object list2I2J(int w, int x, long y, long z) {
  74         return Arrays.asList(w, x, y, z);
  75     }
  76     static Object list2J2I(long w, long x, int y, int z) {
  77         return Arrays.asList(w, x, y, z);
  78     }
  79     static Object listLJJ(Object x, long y, long z) {
  80         return Arrays.asList(x, y, z);
  81     }
  82     static Object listJLJ(long x, Object y, long z) {
  83         return Arrays.asList(x, y, z);
  84     }
  85     static Object listJJL(long x, long y, Object z) {
  86         return Arrays.asList(x, y, z);
  87     }
  88     static Object listJLL(long x, Object y, Object z) {
  89         return Arrays.asList(x, y, z);
  90     }
  91     static Object listLJL(Object x, long y, Object z) {
  92         return Arrays.asList(x, y, z);
  93     }
  94     static Object listLLJ(Object x, Object y, long z) {
  95         return Arrays.asList(x, y, z);
  96     }
  97     static Object listJLLJ(long w, Object x, Object y, long z) {
  98         return Arrays.asList(w, x, y, z);
  99     }
 100     static Object listLJJL(Object w, long x, long y, Object z) {
 101         return Arrays.asList(w, x, y, z);
 102     }
 103     static Object listI_etc(int... va) {
 104         ArrayList<Object> res = new ArrayList<>();
 105         for (int x : va)  res.add(x);
 106         return res;
 107     }
 108     static Object listIJL_etc(int x, long y, Object z, Object... va) {
 109         ArrayList<Object> res = new ArrayList<>();
 110         res.addAll(Arrays.asList(x, y, z));
 111         res.addAll(Arrays.asList(va));
 112         return res;
 113     }
 114 
 115     public static void main(String argv[]) throws Throwable {
 116         if (argv.length > 0) {
 117             for (String arg : argv) {
 118                 // arg ::= name[n,...]
 119                 int k = arg.indexOf('[');
 120                 String mhName = arg.substring(0, k).trim();
 121                 String permString = arg.substring(k);
 122                 testOnePermutation(mhName, permString);
 123             }
 124             return;
 125         }
 126         new PermuteArgsTest().test();
 127     }
 128 
 129     static int testCases;
 130 
 131     @Test
 132     public void test() throws Throwable {
 133         CodeCacheOverflowProcessor.runMHTest(this::test0);
 134     }
 135 
 136     public void test0() throws Throwable {
 137         testCases = 0;
 138         Lookup lookup = lookup();
 139         for (Method m : lookup.lookupClass().getDeclaredMethods()) {
 140             if (m.getName().startsWith("list") &&
 141                 Modifier.isStatic(m.getModifiers())) {
 142                 test(m.getName(), lookup.unreflect(m));
 143             }
 144         }
 145         System.out.println("ran a total of "+testCases+" test cases");
 146     }
 147 
 148     static int jump(int i, int min, int max) {
 149         if (i >= min && i <= max-1) {
 150             // jump faster
 151             int len = max-min;
 152             if (i < min + len/2)
 153                 i = min + len/2;
 154             else
 155                 i = max-1;
 156         }
 157         return i;
 158     }
 159 
 160     static void test(String name, MethodHandle mh) throws Throwable {
 161         if (VERBOSE)
 162             System.out.println("mh = "+name+" : "+mh+" { "
 163                                +Arrays.toString(junkArgs(mh.type().parameterArray())));
 164         int testCases0 = testCases;
 165         if (!mh.isVarargsCollector()) {
 166             // normal case
 167             testPermutations(mh);
 168         } else {
 169             // varargs case; add params up to MAX_ARITY
 170             MethodType mt = mh.type();
 171             int posArgs = mt.parameterCount() - 1;
 172             int arity0 = Math.max(3, posArgs);
 173             for (int arity = arity0; arity <= MAX_ARITY; arity++) {
 174                 MethodHandle mh1;
 175                 try {
 176                     mh1 = adjustArity(mh, arity);
 177                 } catch (IllegalArgumentException ex) {
 178                     System.out.println("*** mh = "+name+" : "+mh+"; arity = "+arity+" => "+ex);
 179                     ex.printStackTrace(System.out);
 180                     break;  // cannot get this arity for this type
 181                 }
 182                 test("("+arity+")"+name, mh1);
 183                 arity = jump(arity, arity0*2, MAX_ARITY);
 184             }
 185         }
 186         if (VERBOSE)
 187             System.out.println("ran "+(testCases - testCases0)+" test cases for "+name+" }");
 188     }
 189 
 190     static MethodHandle adjustArity(MethodHandle mh, int arity) {
 191         MethodType mt = mh.type();
 192         int posArgs = mt.parameterCount() - 1;
 193         Class<?> reptype = mt.parameterType(posArgs).getComponentType();
 194         MethodType mt1 = mt.dropParameterTypes(posArgs, posArgs+1);
 195         while (mt1.parameterCount() < arity) {
 196             Class<?> pt = reptype;
 197             if (pt == Object.class && posArgs > 0)
 198                 // repeat types cyclically if possible:
 199                 pt = mt1.parameterType(mt1.parameterCount() - posArgs);
 200             mt1 = mt1.appendParameterTypes(pt);
 201         }
 202         try {
 203             return mh.asType(mt1);
 204         } catch (WrongMethodTypeException | IllegalArgumentException ex) {
 205             throw new IllegalArgumentException("cannot convert to type "+mt1+" from "+mh, ex);
 206         }
 207     }
 208     static MethodHandle findTestMH(String name, int[] perm) throws ReflectiveOperationException {
 209         int arity = perm.length;
 210         Lookup lookup = lookup();
 211         for (Method m : lookup.lookupClass().getDeclaredMethods()) {
 212             if (m.getName().equals(name) &&
 213                 Modifier.isStatic(m.getModifiers())) {
 214                 MethodHandle mh = lookup.unreflect(m);
 215                 int mhArity = mh.type().parameterCount();
 216                 if (mh.isVarargsCollector()) {
 217                     if (mhArity-1 <= arity)
 218                         return adjustArity(mh, arity);
 219                 } else if (mhArity == arity) {
 220                     return mh;
 221                 }
 222             }
 223         }
 224         throw new RuntimeException("no such method for arity "+arity+": "+name);
 225     }
 226 
 227     static void testPermutations(MethodHandle mh) throws Throwable {
 228         HashSet<String> done = new HashSet<>();
 229         MethodType mt = mh.type();
 230         int[] perm = nullPerm(mt.parameterCount());
 231         final int MARGIN = (perm.length <= 10 ? 2 : 0);
 232         int testCases0 = testCases;
 233         for (int j = 0; j <= 1; j++) {
 234             int maxStart = perm.length-1;
 235             if (j != 0)  maxStart /= 2;
 236             for (int start = 0; start <= maxStart; start++) {
 237                 int maxOmit = (maxStart - start) / 2;
 238                 if (start != 0)  maxOmit = 2;
 239                 if (j != 0)  maxOmit = 1;
 240                 for (int omit = 0; omit <= maxOmit; omit++) {
 241                     int end = perm.length - omit;
 242                     if (end - start >= 2) {
 243                         //System.out.println("testPermutations"+Arrays.asList(start, end)+(j == 0 ? "" : " (reverse)"));
 244                         testPermutations(mh, perm, start, end, done);
 245                     }
 246                     omit = jump(omit, (start == 0 && j == 0 ? MARGIN : 0), maxOmit);
 247                 }
 248                 start = jump(start, (j == 0 ? MARGIN : 0), maxStart);
 249             }
 250             // do everything in reverse:
 251             reverse(perm, 0, perm.length);
 252         }
 253         switch (perm.length) {
 254         case 2: assert(testCases - testCases0 == 2); break;
 255         case 3: assert(testCases - testCases0 == 6); break;
 256         case 4: assert(testCases - testCases0 == 24); break;
 257         case 5: assert(testCases - testCases0 == 120); break;
 258         case 6: assert(testCases - testCases0 > 720/3); break;
 259         }
 260     }
 261 
 262     static void testPermutations(MethodHandle mh, int[] perm, int start, int end, Set<String> done) throws Throwable {
 263         if (end - start <= 1)  return;
 264         for (int j = 0; j <= 1; j++) {
 265             testRotations(mh, perm, start, end, done);
 266             if (end - start <= 2)  return;
 267             reverse(perm, start, end);
 268         }
 269         if (end - start <= 3)  return;
 270         int excess4 = (end - start) - 4;
 271         // composed rotations:
 272         int start2 = start + 1 + excess4/3;
 273         int end2   = end       - excess4/3;
 274         end2 = start2 + Math.min(start == 0 ? 4 : 3, end2 - start2);
 275         int skips = (perm.length+3)/5;
 276         for (int i = start; i < end; i++) {
 277             rotate(perm, start, end);
 278             if (skips > 1 && ((i-start) + (i-start)/7) % skips != 0)  continue;
 279             for (int j = 0; j <= 1; j++) {
 280                 testPermutations(mh, perm, start2, end2, done);
 281                 reverse(perm, start, end);
 282             }
 283         }
 284     }
 285 
 286     static void testRotations(MethodHandle mh, int[] perm, int start, int end, Set<String> done) throws Throwable {
 287         Object[] args = junkArgs(mh.type().parameterArray());
 288         for (int i = start; i < end; i++) {
 289             if (done.add(Arrays.toString(perm)))
 290                 testOnePermutation(mh, perm, args);
 291             rotate(perm, start, end);
 292         }
 293     }
 294 
 295     static void testOnePermutation(MethodHandle mh, int[] perm, Object[] args) throws Throwable {
 296         MethodType mt = mh.type();
 297         MethodType pmt = methodType(mt.returnType(), unpermuteArgs(perm, mt.parameterArray(), Class[].class));
 298         if (VERBOSE)
 299             System.out.println(Arrays.toString(perm));
 300         testCases += 1;
 301         if (DRY_RUN)
 302             return;
 303         Object res = permuteArguments(mh, pmt, perm).invokeWithArguments(unpermuteArgs(perm, args));
 304         String str = String.valueOf(res);
 305         if (!Arrays.toString(args).equals(str)) {
 306             System.out.println(Arrays.toString(perm)+" "+str+" *** WRONG ***");
 307         }
 308     }
 309 
 310     // For reproducing failures:
 311     static void testOnePermutation(String mhName, String permString) throws Throwable {
 312         String s = permString;
 313         s = s.replace('[', ' ').replace(']', ' ').replace(',', ' ');  // easier to trim spaces
 314         s = s.trim();
 315         int[] perm = new int[s.length()];
 316         int arity = 0;
 317         while (!s.isEmpty()) {
 318             int k = s.indexOf(' ');
 319             if (k < 0)  k = s.length();
 320             perm[arity++] = Integer.parseInt(s.substring(0, k));
 321             s = s.substring(k).trim();
 322         }
 323         perm = Arrays.copyOf(perm, arity);
 324         testOnePermutation(mhName, perm);
 325     }
 326     static void testOnePermutation(String mhName, int[] perm) throws Throwable {
 327         MethodHandle mh = findTestMH(mhName, perm);
 328         System.out.println("mh = "+mhName+" : "+mh+" { "
 329                            +Arrays.toString(junkArgs(mh.type().parameterArray())));
 330         Object[] args = junkArgs(mh.type().parameterArray());
 331         testOnePermutation(mh, perm, args);
 332         System.out.println("}");
 333     }
 334 
 335     static Object[] junkArgs(Class<?>[] ptypes) {
 336         Object[] args = new Object[ptypes.length];
 337         for (int i = 0; i < ptypes.length; i++) {
 338             Class<?> pt = ptypes[i];
 339             Object arg;
 340             if (pt == Void.class)       arg = null;
 341             else if (pt == int.class)   arg = i + 101;
 342             else if (pt == long.class)  arg = i + 10_000_000_001L;
 343             else                        arg = "#" + (i + 1);
 344             args[i] = arg;
 345         }
 346         return args;
 347     }
 348 
 349     static int[] nullPerm(int len) {
 350         int[] perm = new int[len];
 351         for (int i = 0; i < len; i++)
 352             perm[i] = i;
 353         return perm;
 354     }
 355     static void rotate(int[] perm) {
 356         rotate(perm, 0, perm.length);
 357     }
 358     static void rotate(int[] perm, int start, int end) {
 359         int x = perm[end-1];
 360         for (int j = start; j < end; j++) {
 361             int y = perm[j]; perm[j] = x; x = y;
 362         }
 363     }
 364     static void reverse(int[] perm) {
 365         reverse(perm, 0, perm.length);
 366     }
 367     static void reverse(int[] perm, int start, int end) {
 368         int mid = start + (end - start)/2;
 369         for (int j = start; j < mid; j++) {
 370             int k = (end-1) - j;
 371             int x = perm[j]; perm[j] = perm[k]; perm[k] = x;
 372         }
 373     }
 374     // Permute the args according to the inverse of perm.
 375     static Object[] unpermuteArgs(int[] perm, Object[] args) {
 376         return unpermuteArgs(perm, args, Object[].class);
 377     }
 378     static <T> T[] unpermuteArgs(int[] perm, T[] args, Class<T[]> Tclass) {
 379         T[] res = Arrays.copyOf(new Object[0], perm.length, Tclass);
 380         for (int i = 0; i < perm.length; i++)
 381             res[perm[i]] = args[i];
 382         return res;
 383     }
 384 }