1 /*
   2  * Copyright (c) 2014, 2015, 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 package test.java.lang.invoke.MethodHandles;
  24 
  25 import com.oracle.testlibrary.jsr292.Helper;
  26 import com.oracle.testlibrary.jsr292.CodeCacheOverflowProcessor;
  27 import jdk.testlibrary.Asserts;
  28 import jdk.testlibrary.TimeLimitedRunner;
  29 import jdk.testlibrary.Utils;
  30 
  31 import java.lang.invoke.MethodHandle;
  32 import java.lang.invoke.MethodHandles;
  33 import java.lang.invoke.MethodType;
  34 import java.lang.reflect.Array;
  35 import java.util.*;
  36 import java.util.function.BiFunction;
  37 import java.util.function.Function;
  38 import java.util.function.Supplier;
  39 
  40 /* @test
  41  * @library /lib/testlibrary/jsr292 /lib/testlibrary/
  42  * @compile CatchExceptionTest.java
  43  * @run main/othervm -esa test.java.lang.invoke.MethodHandles.CatchExceptionTest
  44  * @key intermittent randomness
  45  */
  46 public class CatchExceptionTest {
  47     private static final List<Class<?>> ARGS_CLASSES;
  48     protected static final int MAX_ARITY = Helper.MAX_ARITY - 1;
  49 
  50     static {
  51         Class<?> classes[] = {
  52                 Object.class,
  53                 long.class,
  54                 int.class,
  55                 byte.class,
  56                 Integer[].class,
  57                 double[].class,
  58                 String.class,
  59         };
  60         ARGS_CLASSES = Collections.unmodifiableList(
  61                 Helper.randomClasses(classes, MAX_ARITY));
  62     }
  63 
  64     private final TestCase testCase;
  65     private final int nargs;
  66     private final int argsCount;
  67     private final MethodHandle catcher;
  68     private int dropped;
  69     private MethodHandle thrower;
  70 
  71     public CatchExceptionTest(TestCase testCase, final boolean isVararg, final int argsCount,
  72             final int catchDrops) {
  73         this.testCase = testCase;
  74         this.dropped = catchDrops;
  75         MethodHandle thrower = testCase.thrower;
  76         int throwerLen = thrower.type().parameterCount();
  77         List<Class<?>> classes;
  78         int extra = Math.max(0, argsCount - throwerLen);
  79         classes = getThrowerParams(isVararg, extra);
  80         this.argsCount = throwerLen + classes.size();
  81         thrower = Helper.addTrailingArgs(thrower, this.argsCount, classes);
  82         if (isVararg && argsCount > throwerLen) {
  83             MethodType mt = thrower.type();
  84             Class<?> lastParam = mt.parameterType(mt.parameterCount() - 1);
  85             thrower = thrower.asVarargsCollector(lastParam);
  86         }
  87         this.thrower = thrower;
  88         this.dropped = Math.min(this.argsCount, catchDrops);
  89         catcher = testCase.getCatcher(getCatcherParams());
  90         nargs = Math.max(2, this.argsCount);
  91     }
  92 
  93     public static void main(String[] args) throws Throwable {
  94         CodeCacheOverflowProcessor.runMHTest(CatchExceptionTest::test);
  95     }
  96 
  97     public static void test() throws Throwable {
  98         System.out.println("classes = " + ARGS_CLASSES);
  99 
 100         TestFactory factory = new TestFactory();
 101         long timeout = Helper.IS_THOROUGH ? 0L : Utils.adjustTimeout(Utils.DEFAULT_TEST_TIMEOUT);
 102         // subtract vm init time and reserve time for vm exit
 103         timeout *= 0.9;
 104         TimeLimitedRunner runner = new TimeLimitedRunner(timeout, 2.0d,
 105                 () -> {
 106                     CatchExceptionTest test = factory.nextTest();
 107                     if (test != null) {
 108                         test.runTest();
 109                         return true;
 110                     }
 111                     return false;
 112                 });
 113         for (CatchExceptionTest test : TestFactory.MANDATORY_TEST_CASES) {
 114             test.runTest();
 115         }
 116         runner.call();
 117     }
 118 
 119     private List<Class<?>> getThrowerParams(boolean isVararg, int argsCount) {
 120         return Helper.getParams(ARGS_CLASSES, isVararg, argsCount);
 121     }
 122 
 123     private List<Class<?>> getCatcherParams() {
 124         int catchArgc = 1 + this.argsCount - dropped;
 125         List<Class<?>> result = new ArrayList<>(
 126                 thrower.type().parameterList().subList(0, catchArgc - 1));
 127         // prepend throwable
 128         result.add(0, testCase.throwableClass);
 129         return result;
 130     }
 131 
 132     private void runTest() {
 133         if (Helper.IS_VERBOSE) {
 134             System.out.printf("CatchException(%s, isVararg=%b argsCount=%d " +
 135                             "dropped=%d)%n",
 136                     testCase, thrower.isVarargsCollector(), argsCount, dropped);
 137         }
 138 
 139         Helper.clear();
 140 
 141         Object[] args = Helper.randomArgs(
 142                 argsCount, thrower.type().parameterArray());
 143         Object arg0 = Helper.MISSING_ARG;
 144         Object arg1 = testCase.thrown;
 145         if (argsCount > 0) {
 146             arg0 = args[0];
 147         }
 148         if (argsCount > 1) {
 149             args[1] = arg1;
 150         }
 151         Asserts.assertEQ(nargs, thrower.type().parameterCount());
 152         if (argsCount < nargs) {
 153             Object[] appendArgs = {arg0, arg1};
 154             appendArgs = Arrays.copyOfRange(appendArgs, argsCount, nargs);
 155             thrower = MethodHandles.insertArguments(
 156                     thrower, argsCount, appendArgs);
 157         }
 158         Asserts.assertEQ(argsCount, thrower.type().parameterCount());
 159 
 160         MethodHandle target = MethodHandles.catchException(
 161                 testCase.filter(thrower), testCase.throwableClass,
 162                 testCase.filter(catcher));
 163 
 164         Asserts.assertEQ(thrower.type(), target.type());
 165         Asserts.assertEQ(argsCount, target.type().parameterCount());
 166 
 167         Object returned;
 168         try {
 169             returned = target.invokeWithArguments(args);
 170         } catch (Throwable ex) {
 171             if (CodeCacheOverflowProcessor.isThrowableCausedByVME(ex)) {
 172                 throw new Error(ex);
 173             }
 174             testCase.assertCatch(ex);
 175             returned = ex;
 176         }
 177 
 178         testCase.assertReturn(returned, arg0, arg1, dropped, args);
 179     }
 180 }
 181 
 182 class TestFactory {
 183     public static final List<CatchExceptionTest> MANDATORY_TEST_CASES = new ArrayList<>();
 184 
 185     private static final int MIN_TESTED_ARITY = 10;
 186 
 187     static {
 188         for (int[] args : new int[][]{
 189                 {0, 0},
 190                 {MIN_TESTED_ARITY, 0},
 191                 {MIN_TESTED_ARITY, MIN_TESTED_ARITY},
 192                 {CatchExceptionTest.MAX_ARITY, 0},
 193                 {CatchExceptionTest.MAX_ARITY, CatchExceptionTest.MAX_ARITY},
 194         }) {
 195                 MANDATORY_TEST_CASES.addAll(createTests(args[0], args[1]));
 196         }
 197     }
 198 
 199     private int count;
 200     private int args;
 201     private int dropArgs;
 202     private int currentMaxDrops;
 203     private int maxArgs;
 204     private int maxDrops;
 205     private int constructor;
 206     private int constructorSize;
 207     private boolean isVararg;
 208 
 209     public TestFactory() {
 210         if (Helper.IS_THOROUGH) {
 211             maxArgs = maxDrops = CatchExceptionTest.MAX_ARITY;
 212         } else {
 213             maxArgs = MIN_TESTED_ARITY
 214                     + Helper.RNG.nextInt(CatchExceptionTest.MAX_ARITY
 215                             - MIN_TESTED_ARITY)
 216                     + 1;
 217             maxDrops = MIN_TESTED_ARITY
 218                     + Helper.RNG.nextInt(maxArgs - MIN_TESTED_ARITY)
 219                     + 1;
 220             args = 1;
 221         }
 222 
 223         System.out.printf("maxArgs = %d%nmaxDrops = %d%n", maxArgs, maxDrops);
 224         constructorSize = TestCase.CONSTRUCTORS.size();
 225     }
 226 
 227     private static List<CatchExceptionTest> createTests(int argsCount,
 228             int catchDrops) {
 229         if (catchDrops > argsCount || argsCount < 0 || catchDrops < 0) {
 230             throw new IllegalArgumentException("argsCount = " + argsCount
 231                     + ", catchDrops = " + catchDrops
 232             );
 233         }
 234         List<CatchExceptionTest> result = new ArrayList<>(
 235                 TestCase.CONSTRUCTORS.size());
 236         for (Supplier<TestCase> constructor : TestCase.CONSTRUCTORS) {
 237             result.add(new CatchExceptionTest(constructor.get(),
 238                     /* isVararg = */ true,
 239                     argsCount,
 240                     catchDrops));
 241             result.add(new CatchExceptionTest(constructor.get(),
 242                     /* isVararg = */ false,
 243                     argsCount,
 244                     catchDrops));
 245         }
 246         return result;
 247     }
 248 
 249     /**
 250      * @return next test from test matrix:
 251      * {varArgs, noVarArgs} x TestCase.rtypes x TestCase.THROWABLES x {1, .., maxArgs } x {0, .., maxDrops}
 252      */
 253     public CatchExceptionTest nextTest() {
 254         if (constructor < constructorSize) {
 255             return createTest();
 256         }
 257         constructor = 0;
 258         count++;
 259         if (!Helper.IS_THOROUGH && count > Helper.TEST_LIMIT) {
 260             System.out.println("test limit is exceeded");
 261             return null;
 262         }
 263         if (dropArgs <= currentMaxDrops) {
 264             if (dropArgs == 0) {
 265                 if (Helper.IS_THOROUGH || Helper.RNG.nextBoolean()) {
 266                     ++dropArgs;
 267                     return createTest();
 268                 } else if (Helper.IS_VERBOSE) {
 269                     System.out.printf(
 270                             "argsCount=%d : \"drop\" scenarios are skipped%n",
 271                             args);
 272                 }
 273             } else {
 274                 ++dropArgs;
 275                 return createTest();
 276             }
 277         }
 278 
 279         if (args < maxArgs) {
 280             dropArgs = 0;
 281             currentMaxDrops = Math.min(args, maxDrops);
 282             ++args;
 283             return createTest();
 284         }
 285         return null;
 286     }
 287 
 288     private CatchExceptionTest createTest() {
 289         if (!Helper.IS_THOROUGH) {
 290             return new CatchExceptionTest(
 291                     TestCase.CONSTRUCTORS.get(constructor++).get(),
 292                     Helper.RNG.nextBoolean(), args, dropArgs);
 293         } else {
 294            if (isVararg) {
 295                isVararg = false;
 296                return new CatchExceptionTest(
 297                        TestCase.CONSTRUCTORS.get(constructor++).get(),
 298                        isVararg, args, dropArgs);
 299            } else {
 300                isVararg = true;
 301                return new CatchExceptionTest(
 302                        TestCase.CONSTRUCTORS.get(constructor).get(),
 303                        isVararg, args, dropArgs);
 304            }
 305         }
 306     }
 307 }
 308 
 309 class TestCase<T> {
 310     private static enum ThrowMode {
 311         NOTHING,
 312         CAUGHT,
 313         UNCAUGHT,
 314         ADAPTER
 315     }
 316 
 317     @SuppressWarnings("unchecked")
 318     public static final List<Supplier<TestCase>> CONSTRUCTORS;
 319     private static final MethodHandle FAKE_IDENTITY;
 320     private static final MethodHandle THROW_OR_RETURN;
 321     private static final MethodHandle CATCHER;
 322 
 323     static {
 324         try {
 325             MethodHandles.Lookup lookup = MethodHandles.lookup();
 326             THROW_OR_RETURN = lookup.findStatic(
 327                     TestCase.class,
 328                     "throwOrReturn",
 329                     MethodType.methodType(Object.class, Object.class,
 330                             Throwable.class)
 331             );
 332             CATCHER = lookup.findStatic(
 333                     TestCase.class,
 334                     "catcher",
 335                     MethodType.methodType(Object.class, Object.class));
 336             FAKE_IDENTITY = lookup.findVirtual(
 337                     TestCase.class, "fakeIdentity",
 338                     MethodType.methodType(Object.class, Object.class));
 339 
 340         } catch (NoSuchMethodException | IllegalAccessException e) {
 341             throw new Error(e);
 342         }
 343         PartialConstructor[] constructors = {
 344                 create(Object.class, Object.class::cast),
 345                 create(String.class, Objects::toString),
 346                 create(int[].class, x -> new int[]{Objects.hashCode(x)}),
 347                 create(long.class,
 348                         x -> Objects.hashCode(x) & (-1L >>> 32)),
 349                 create(void.class, TestCase::noop)};
 350         Throwable[] throwables = {
 351                 new ClassCastException("testing"),
 352                 new java.io.IOException("testing"),
 353                 new LinkageError("testing")};
 354         List<Supplier<TestCase>> list = new ArrayList<>(constructors.length *
 355                 throwables.length * ThrowMode.values().length);
 356         //noinspection unchecked
 357         for (PartialConstructor f : constructors) {
 358             for (ThrowMode mode : ThrowMode.values()) {
 359                 for (Throwable t : throwables) {
 360                     list.add(f.apply(mode, t));
 361                 }
 362             }
 363         }
 364         CONSTRUCTORS = Collections.unmodifiableList(list);
 365     }
 366 
 367     public final Class<T> rtype;
 368     public final ThrowMode throwMode;
 369     public final Throwable thrown;
 370     public final Class<? extends Throwable> throwableClass;
 371     /**
 372      * MH which takes 2 args (Object,Throwable), 1st is the return value,
 373      * 2nd is the exception which will be thrown, if it's supposed in current
 374      * {@link #throwMode}.
 375      */
 376     public final MethodHandle thrower;
 377     private final Function<Object, T> cast;
 378     protected MethodHandle filter;
 379     private int fakeIdentityCount;
 380 
 381     private TestCase(Class<T> rtype, Function<Object, T> cast,
 382             ThrowMode throwMode, Throwable thrown)
 383             throws NoSuchMethodException, IllegalAccessException {
 384         this.cast = cast;
 385         filter = MethodHandles.lookup().findVirtual(
 386                 Function.class,
 387                 "apply",
 388                 MethodType.methodType(Object.class, Object.class))
 389                               .bindTo(cast);
 390         this.rtype = rtype;
 391         this.throwMode = throwMode;
 392         this.throwableClass = thrown.getClass();
 393         switch (throwMode) {
 394             case NOTHING:
 395                 this.thrown = null;
 396                 break;
 397             case ADAPTER:
 398             case UNCAUGHT:
 399                 this.thrown = new Error("do not catch this");
 400                 break;
 401             default:
 402                 this.thrown = thrown;
 403         }
 404 
 405         MethodHandle throwOrReturn = THROW_OR_RETURN;
 406         if (throwMode == ThrowMode.ADAPTER) {
 407             MethodHandle fakeIdentity = FAKE_IDENTITY.bindTo(this);
 408             for (int i = 0; i < 10; ++i) {
 409                 throwOrReturn = MethodHandles.filterReturnValue(
 410                         throwOrReturn, fakeIdentity);
 411             }
 412         }
 413         thrower = throwOrReturn.asType(MethodType.genericMethodType(2));
 414     }
 415 
 416     private static Void noop(Object x) {
 417         return null;
 418     }
 419 
 420     private static <T2> PartialConstructor create(
 421             Class<T2> rtype, Function<Object, T2> cast) {
 422         return (t, u) -> () -> {
 423             try {
 424                 return new TestCase<>(rtype, cast, t, u);
 425             } catch (NoSuchMethodException | IllegalAccessException e) {
 426                 throw new Error(e);
 427             }
 428         };
 429     }
 430 
 431     private static <T extends Throwable>
 432     Object throwOrReturn(Object normal, T exception) throws T {
 433         if (exception != null) {
 434             Helper.called("throwOrReturn/throw", normal, exception);
 435             throw exception;
 436         }
 437         Helper.called("throwOrReturn/normal", normal, exception);
 438         return normal;
 439     }
 440 
 441     private static <T extends Throwable>
 442     Object catcher(Object o) {
 443         Helper.called("catcher", o);
 444         return o;
 445     }
 446 
 447     public MethodHandle filter(MethodHandle target) {
 448         return MethodHandles.filterReturnValue(target, filter);
 449     }
 450 
 451     public MethodHandle getCatcher(List<Class<?>> classes) {
 452         return MethodHandles.filterReturnValue(Helper.AS_LIST.asType(
 453                         MethodType.methodType(Object.class, classes)),
 454                 CATCHER
 455         );
 456     }
 457 
 458     @Override
 459     public String toString() {
 460         return "TestCase{" +
 461                 "rtype=" + rtype +
 462                 ", throwMode=" + throwMode +
 463                 ", throwableClass=" + throwableClass +
 464                 '}';
 465     }
 466 
 467     public String callName() {
 468         return "throwOrReturn/" +
 469                 (throwMode == ThrowMode.NOTHING
 470                         ? "normal"
 471                         : "throw");
 472     }
 473 
 474     public void assertReturn(Object returned, Object arg0, Object arg1,
 475             int catchDrops, Object... args) {
 476         int lag = 0;
 477         if (throwMode == ThrowMode.CAUGHT) {
 478             lag = 1;
 479         }
 480         Helper.assertCalled(lag, callName(), arg0, arg1);
 481 
 482         if (throwMode == ThrowMode.NOTHING) {
 483             assertEQ(cast.apply(arg0), returned);
 484         } else if (throwMode == ThrowMode.CAUGHT) {
 485             List<Object> catchArgs = new ArrayList<>(Arrays.asList(args));
 486             // catcher receives an initial subsequence of target arguments:
 487             catchArgs.subList(args.length - catchDrops, args.length).clear();
 488             // catcher also receives the exception, prepended:
 489             catchArgs.add(0, thrown);
 490             Helper.assertCalled("catcher", catchArgs);
 491             assertEQ(cast.apply(catchArgs), returned);
 492         }
 493         Asserts.assertEQ(0, fakeIdentityCount);
 494     }
 495 
 496     private void assertEQ(T t, Object returned) {
 497         if (rtype.isArray()) {
 498             Asserts.assertEQ(t.getClass(), returned.getClass());
 499             int n = Array.getLength(t);
 500             Asserts.assertEQ(n, Array.getLength(returned));
 501             for (int i = 0; i < n; ++i) {
 502                 Asserts.assertEQ(Array.get(t, i), Array.get(returned, i));
 503             }
 504         } else {
 505             Asserts.assertEQ(t, returned);
 506         }
 507     }
 508 
 509     private Object fakeIdentity(Object x) {
 510         System.out.println("should throw through this!");
 511         ++fakeIdentityCount;
 512         return x;
 513     }
 514 
 515     public void assertCatch(Throwable ex) {
 516         try {
 517             Asserts.assertSame(thrown, ex,
 518                     "must get the out-of-band exception");
 519         } catch (Throwable t) {
 520             ex.printStackTrace();
 521         }
 522     }
 523 
 524     public interface PartialConstructor
 525             extends BiFunction<ThrowMode, Throwable, Supplier<TestCase>> {
 526     }
 527 }