1 /*
   2  * Copyright (c) 2008, 2013, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import java.security.AccessController;
  29 import java.security.PrivilegedAction;
  30 import java.util.ArrayList;
  31 import java.util.Arrays;
  32 import java.util.Collections;
  33 
  34 import sun.invoke.empty.Empty;
  35 import sun.invoke.util.ValueConversions;
  36 import sun.invoke.util.VerifyType;
  37 import sun.invoke.util.Wrapper;
  38 import sun.reflect.CallerSensitive;
  39 import sun.reflect.Reflection;
  40 import static java.lang.invoke.LambdaForm.*;
  41 import static java.lang.invoke.MethodHandleStatics.*;
  42 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  43 
  44 /**
  45  * Trusted implementation code for MethodHandle.
  46  * @author jrose
  47  */
  48 /*non-public*/ abstract class MethodHandleImpl {
  49     // Do not adjust this except for special platforms:
  50     private static final int MAX_ARITY;
  51     static {
  52         final Object[] values = { 255 };
  53         AccessController.doPrivileged(new PrivilegedAction<Void>() {
  54             @Override
  55             public Void run() {
  56                 values[0] = Integer.getInteger(MethodHandleImpl.class.getName()+".MAX_ARITY", 255);
  57                 return null;
  58             }
  59         });
  60         MAX_ARITY = (Integer) values[0];
  61     }
  62 
  63     /// Factory methods to create method handles:
  64 
  65     static void initStatics() {
  66         // Trigger selected static initializations.
  67         MemberName.Factory.INSTANCE.getClass();
  68     }
  69 
  70     static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, boolean isSetter) {
  71         if (arrayClass == Object[].class)
  72             return (isSetter ? ArrayAccessor.OBJECT_ARRAY_SETTER : ArrayAccessor.OBJECT_ARRAY_GETTER);
  73         if (!arrayClass.isArray())
  74             throw newIllegalArgumentException("not an array: "+arrayClass);
  75         MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass);
  76         int cacheIndex = (isSetter ? ArrayAccessor.SETTER_INDEX : ArrayAccessor.GETTER_INDEX);
  77         MethodHandle mh = cache[cacheIndex];
  78         if (mh != null)  return mh;
  79         mh = ArrayAccessor.getAccessor(arrayClass, isSetter);
  80         MethodType correctType = ArrayAccessor.correctType(arrayClass, isSetter);
  81         if (mh.type() != correctType) {
  82             assert(mh.type().parameterType(0) == Object[].class);
  83             assert((isSetter ? mh.type().parameterType(2) : mh.type().returnType()) == Object.class);
  84             assert(isSetter || correctType.parameterType(0).getComponentType() == correctType.returnType());
  85             // safe to view non-strictly, because element type follows from array type
  86             mh = mh.viewAsType(correctType, false);
  87         }
  88         mh = makeIntrinsic(mh, (isSetter ? Intrinsic.ARRAY_STORE : Intrinsic.ARRAY_LOAD));
  89         // Atomically update accessor cache.
  90         synchronized(cache) {
  91             if (cache[cacheIndex] == null) {
  92                 cache[cacheIndex] = mh;
  93             } else {
  94                 // Throw away newly constructed accessor and use cached version.
  95                 mh = cache[cacheIndex];
  96             }
  97         }
  98         return mh;
  99     }
 100 
 101     static final class ArrayAccessor {
 102         /// Support for array element access
 103         static final int GETTER_INDEX = 0, SETTER_INDEX = 1, INDEX_LIMIT = 2;
 104         static final ClassValue<MethodHandle[]> TYPED_ACCESSORS
 105                 = new ClassValue<MethodHandle[]>() {
 106                     @Override
 107                     protected MethodHandle[] computeValue(Class<?> type) {
 108                         return new MethodHandle[INDEX_LIMIT];
 109                     }
 110                 };
 111         static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER;
 112         static {
 113             MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class);
 114             cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, false), Intrinsic.ARRAY_LOAD);
 115             cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, true),  Intrinsic.ARRAY_STORE);
 116 
 117             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName()));
 118             assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName()));
 119         }
 120 
 121         static int     getElementI(int[]     a, int i)            { return              a[i]; }
 122         static long    getElementJ(long[]    a, int i)            { return              a[i]; }
 123         static float   getElementF(float[]   a, int i)            { return              a[i]; }
 124         static double  getElementD(double[]  a, int i)            { return              a[i]; }
 125         static boolean getElementZ(boolean[] a, int i)            { return              a[i]; }
 126         static byte    getElementB(byte[]    a, int i)            { return              a[i]; }
 127         static short   getElementS(short[]   a, int i)            { return              a[i]; }
 128         static char    getElementC(char[]    a, int i)            { return              a[i]; }
 129         static Object  getElementL(Object[]  a, int i)            { return              a[i]; }
 130 
 131         static void    setElementI(int[]     a, int i, int     x) {              a[i] = x; }
 132         static void    setElementJ(long[]    a, int i, long    x) {              a[i] = x; }
 133         static void    setElementF(float[]   a, int i, float   x) {              a[i] = x; }
 134         static void    setElementD(double[]  a, int i, double  x) {              a[i] = x; }
 135         static void    setElementZ(boolean[] a, int i, boolean x) {              a[i] = x; }
 136         static void    setElementB(byte[]    a, int i, byte    x) {              a[i] = x; }
 137         static void    setElementS(short[]   a, int i, short   x) {              a[i] = x; }
 138         static void    setElementC(char[]    a, int i, char    x) {              a[i] = x; }
 139         static void    setElementL(Object[]  a, int i, Object  x) {              a[i] = x; }
 140 
 141         static String name(Class<?> arrayClass, boolean isSetter) {
 142             Class<?> elemClass = arrayClass.getComponentType();
 143             if (elemClass == null)  throw newIllegalArgumentException("not an array", arrayClass);
 144             return (!isSetter ? "getElement" : "setElement") + Wrapper.basicTypeChar(elemClass);
 145         }
 146         static MethodType type(Class<?> arrayClass, boolean isSetter) {
 147             Class<?> elemClass = arrayClass.getComponentType();
 148             Class<?> arrayArgClass = arrayClass;
 149             if (!elemClass.isPrimitive()) {
 150                 arrayArgClass = Object[].class;
 151                 elemClass = Object.class;
 152             }
 153             return !isSetter ?
 154                     MethodType.methodType(elemClass,  arrayArgClass, int.class) :
 155                     MethodType.methodType(void.class, arrayArgClass, int.class, elemClass);
 156         }
 157         static MethodType correctType(Class<?> arrayClass, boolean isSetter) {
 158             Class<?> elemClass = arrayClass.getComponentType();
 159             return !isSetter ?
 160                     MethodType.methodType(elemClass,  arrayClass, int.class) :
 161                     MethodType.methodType(void.class, arrayClass, int.class, elemClass);
 162         }
 163         static MethodHandle getAccessor(Class<?> arrayClass, boolean isSetter) {
 164             String     name = name(arrayClass, isSetter);
 165             MethodType type = type(arrayClass, isSetter);
 166             try {
 167                 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type);
 168             } catch (ReflectiveOperationException ex) {
 169                 throw uncaughtException(ex);
 170             }
 171         }
 172     }
 173 
 174     /**
 175      * Create a JVM-level adapter method handle to conform the given method
 176      * handle to the similar newType, using only pairwise argument conversions.
 177      * For each argument, convert incoming argument to the exact type needed.
 178      * The argument conversions allowed are casting, boxing and unboxing,
 179      * integral widening or narrowing, and floating point widening or narrowing.
 180      * @param srcType required call type
 181      * @param target original method handle
 182      * @param strict if true, only asType conversions are allowed; if false, explicitCastArguments conversions allowed
 183      * @param monobox if true, unboxing conversions are assumed to be exactly typed (Integer to int only, not long or double)
 184      * @return an adapter to the original handle with the desired new type,
 185      *          or the original target if the types are already identical
 186      *          or null if the adaptation cannot be made
 187      */
 188     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 189                                             boolean strict, boolean monobox) {
 190         MethodType dstType = target.type();
 191         assert(dstType.parameterCount() == target.type().parameterCount());
 192         if (srcType == dstType)
 193             return target;
 194         return makePairwiseConvertIndirect(target, srcType, strict, monobox);
 195     }
 196 
 197     private static int countNonNull(Object[] array) {
 198         int count = 0;
 199         for (Object x : array) {
 200             if (x != null)  ++count;
 201         }
 202         return count;
 203     }
 204 
 205     static MethodHandle makePairwiseConvertIndirect(MethodHandle target, MethodType srcType,
 206                                                     boolean strict, boolean monobox) {
 207         // Calculate extra arguments (temporaries) required in the names array.
 208         Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox);
 209         final int INARG_COUNT = srcType.parameterCount();
 210         int convCount = countNonNull(convSpecs);
 211         boolean retConv = (convSpecs[INARG_COUNT] != null);
 212         boolean retVoid = srcType.returnType() == void.class;
 213         if (retConv && retVoid) {
 214             convCount -= 1;
 215             retConv = false;
 216         }
 217 
 218         final int IN_MH         = 0;
 219         final int INARG_BASE    = 1;
 220         final int INARG_LIMIT   = INARG_BASE + INARG_COUNT;
 221         final int NAME_LIMIT    = INARG_LIMIT + convCount + 1;
 222         final int RETURN_CONV   = (!retConv ? -1         : NAME_LIMIT - 1);
 223         final int OUT_CALL      = (!retConv ? NAME_LIMIT : RETURN_CONV) - 1;
 224         final int RESULT        = (retVoid ? -1 : NAME_LIMIT - 1);
 225 
 226         // Now build a LambdaForm.
 227         MethodType lambdaType = srcType.basicType().invokerType();
 228         Name[] names = arguments(NAME_LIMIT - INARG_LIMIT, lambdaType);
 229 
 230         // Collect the arguments to the outgoing call, maybe with conversions:
 231         final int OUTARG_BASE = 0;  // target MH is Name.function, name Name.arguments[0]
 232         Object[] outArgs = new Object[OUTARG_BASE + INARG_COUNT];
 233 
 234         int nameCursor = INARG_LIMIT;
 235         for (int i = 0; i < INARG_COUNT; i++) {
 236             Object convSpec = convSpecs[i];
 237             if (convSpec == null) {
 238                 // do nothing: difference is trivial
 239                 outArgs[OUTARG_BASE + i] = names[INARG_BASE + i];
 240                 continue;
 241             }
 242 
 243             Name conv;
 244             if (convSpec instanceof Class) {
 245                 Class<?> convClass = (Class<?>) convSpec;
 246                 conv = new Name(Lazy.MH_castReference, convClass, names[INARG_BASE + i]);
 247             } else {
 248                 MethodHandle fn = (MethodHandle) convSpec;
 249                 conv = new Name(fn, names[INARG_BASE + i]);
 250             }
 251             assert(names[nameCursor] == null);
 252             names[nameCursor++] = conv;
 253             assert(outArgs[OUTARG_BASE + i] == null);
 254             outArgs[OUTARG_BASE + i] = conv;
 255         }
 256 
 257         // Build argument array for the call.
 258         assert(nameCursor == OUT_CALL);
 259         names[OUT_CALL] = new Name(target, outArgs);
 260 
 261         Object convSpec = convSpecs[INARG_COUNT];
 262         if (!retConv) {
 263             assert(OUT_CALL == names.length-1);
 264         } else {
 265             Name conv;
 266             if (convSpec == void.class) {
 267                 conv = new Name(LambdaForm.constantZero(BasicType.basicType(srcType.returnType())));
 268             } else if (convSpec instanceof Class) {
 269                 Class<?> convClass = (Class<?>) convSpec;
 270                 conv = new Name(Lazy.MH_castReference, convClass, names[OUT_CALL]);
 271             } else {
 272                 MethodHandle fn = (MethodHandle) convSpec;
 273                 if (fn.type().parameterCount() == 0)
 274                     conv = new Name(fn);  // don't pass retval to void conversion
 275                 else
 276                     conv = new Name(fn, names[OUT_CALL]);
 277             }
 278             assert(names[RETURN_CONV] == null);
 279             names[RETURN_CONV] = conv;
 280             assert(RETURN_CONV == names.length-1);
 281         }
 282 
 283         LambdaForm form = new LambdaForm("convert", lambdaType.parameterCount(), names, RESULT);
 284         return SimpleMethodHandle.make(srcType, form);
 285     }
 286 
 287     /**
 288      * Identity function, with reference cast.
 289      * @param t an arbitrary reference type
 290      * @param x an arbitrary reference value
 291      * @return the same value x
 292      */
 293     @ForceInline
 294     @SuppressWarnings("unchecked")
 295     static <T,U> T castReference(Class<? extends T> t, U x) {
 296         // inlined Class.cast because we can't ForceInline it
 297         if (x != null && !t.isInstance(x))
 298             throw newClassCastException(t, x);
 299         return (T) x;
 300     }
 301 
 302     private static ClassCastException newClassCastException(Class<?> t, Object obj) {
 303         return new ClassCastException("Cannot cast " + obj.getClass().getName() + " to " + t.getName());
 304     }
 305 
 306     static MethodHandle makeReferenceIdentity(Class<?> refType) {
 307         MethodType lambdaType = MethodType.genericMethodType(1).invokerType();
 308         Name[] names = arguments(1, lambdaType);
 309         names[names.length - 1] = new Name(ValueConversions.identity(), names[1]);
 310         LambdaForm form = new LambdaForm("identity", lambdaType.parameterCount(), names);
 311         return SimpleMethodHandle.make(MethodType.methodType(refType, refType), form);
 312     }
 313 
 314     static Object[] computeValueConversions(MethodType srcType, MethodType dstType,
 315                                             boolean strict, boolean monobox) {
 316         final int INARG_COUNT = srcType.parameterCount();
 317         Object[] convSpecs = new Object[INARG_COUNT+1];
 318         for (int i = 0; i <= INARG_COUNT; i++) {
 319             boolean isRet = (i == INARG_COUNT);
 320             Class<?> src = isRet ? dstType.returnType() : srcType.parameterType(i);
 321             Class<?> dst = isRet ? srcType.returnType() : dstType.parameterType(i);
 322             if (!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)) {
 323                 convSpecs[i] = valueConversion(src, dst, strict, monobox);
 324             }
 325         }
 326         return convSpecs;
 327     }
 328     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType,
 329                                             boolean strict) {
 330         return makePairwiseConvert(target, srcType, strict, /*monobox=*/ false);
 331     }
 332 
 333     /**
 334      * Find a conversion function from the given source to the given destination.
 335      * This conversion function will be used as a LF NamedFunction.
 336      * Return a Class object if a simple cast is needed.
 337      * Return void.class if void is involved.
 338      */
 339     static Object valueConversion(Class<?> src, Class<?> dst, boolean strict, boolean monobox) {
 340         assert(!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict));  // caller responsibility
 341         if (dst == void.class)
 342             return dst;
 343         MethodHandle fn;
 344         if (src.isPrimitive()) {
 345             if (src == void.class) {
 346                 return void.class;  // caller must recognize this specially
 347             } else if (dst.isPrimitive()) {
 348                 // Examples: int->byte, byte->int, boolean->int (!strict)
 349                 fn = ValueConversions.convertPrimitive(src, dst);
 350             } else {
 351                 // Examples: int->Integer, boolean->Object, float->Number
 352                 Wrapper wsrc = Wrapper.forPrimitiveType(src);
 353                 fn = ValueConversions.boxExact(wsrc);
 354                 assert(fn.type().parameterType(0) == wsrc.primitiveType());
 355                 assert(fn.type().returnType() == wsrc.wrapperType());
 356                 if (!VerifyType.isNullConversion(wsrc.wrapperType(), dst, strict)) {
 357                     // Corner case, such as int->Long, which will probably fail.
 358                     MethodType mt = MethodType.methodType(dst, src);
 359                     if (strict)
 360                         fn = fn.asType(mt);
 361                     else
 362                         fn = MethodHandleImpl.makePairwiseConvert(fn, mt, /*strict=*/ false);
 363                 }
 364             }
 365         } else {
 366             if (dst.isPrimitive()) {
 367                 Wrapper wdst = Wrapper.forPrimitiveType(dst);
 368                 if (monobox || src == wdst.wrapperType()) {
 369                     // Use a strongly-typed unboxer, if possible.
 370                     fn = ValueConversions.unboxExact(wdst, strict);
 371                 } else {
 372                     // Examples:  Object->int, Number->int, Comparable->int, Byte->int
 373                     // must include additional conversions
 374                     // src must be examined at runtime, to detect Byte, Character, etc.
 375                     fn = (strict
 376                           ? ValueConversions.unboxWiden(wdst)
 377                           : ValueConversions.unboxCast(wdst));
 378                 }
 379             } else {
 380                 // Simple reference conversion.
 381                 // Note:  Do not check for a class hierarchy relation
 382                 // between src and dst.  In all cases a 'null' argument
 383                 // will pass the cast conversion.
 384                 return dst;
 385             }
 386         }
 387         assert(fn.type().parameterCount() <= 1) : "pc"+Arrays.asList(src.getSimpleName(), dst.getSimpleName(), fn);
 388         return fn;
 389     }
 390 
 391     static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) {
 392         MethodType type = target.type();
 393         int last = type.parameterCount() - 1;
 394         if (type.parameterType(last) != arrayType)
 395             target = target.asType(type.changeParameterType(last, arrayType));
 396         target = target.asFixedArity();  // make sure this attribute is turned off
 397         return new AsVarargsCollector(target, arrayType);
 398     }
 399 
 400     private static final class AsVarargsCollector extends DelegatingMethodHandle {
 401         private final MethodHandle target;
 402         private final Class<?> arrayType;
 403         private @Stable MethodHandle asCollectorCache;
 404 
 405         AsVarargsCollector(MethodHandle target, Class<?> arrayType) {
 406             this(target.type(), target, arrayType);
 407         }
 408         AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) {
 409             super(type, target);
 410             this.target = target;
 411             this.arrayType = arrayType;
 412             this.asCollectorCache = target.asCollector(arrayType, 0);
 413         }
 414 
 415         @Override
 416         public boolean isVarargsCollector() {
 417             return true;
 418         }
 419 
 420         @Override
 421         protected MethodHandle getTarget() {
 422             return target;
 423         }
 424 
 425         @Override
 426         public MethodHandle asFixedArity() {
 427             return target;
 428         }
 429 
 430         @Override
 431         MethodHandle setVarargs(MemberName member) {
 432             if (member.isVarargs())  return this;
 433             return asFixedArity();
 434         }
 435 
 436         @Override
 437         public MethodHandle asTypeUncached(MethodType newType) {
 438             MethodType type = this.type();
 439             int collectArg = type.parameterCount() - 1;
 440             int newArity = newType.parameterCount();
 441             if (newArity == collectArg+1 &&
 442                 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
 443                 // if arity and trailing parameter are compatible, do normal thing
 444                 return asTypeCache = asFixedArity().asType(newType);
 445             }
 446             // check cache
 447             MethodHandle acc = asCollectorCache;
 448             if (acc != null && acc.type().parameterCount() == newArity)
 449                 return asTypeCache = acc.asType(newType);
 450             // build and cache a collector
 451             int arrayLength = newArity - collectArg;
 452             MethodHandle collector;
 453             try {
 454                 collector = asFixedArity().asCollector(arrayType, arrayLength);
 455                 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector;
 456             } catch (IllegalArgumentException ex) {
 457                 throw new WrongMethodTypeException("cannot build collector", ex);
 458             }
 459             asCollectorCache = collector;
 460             return asTypeCache = collector.asType(newType);
 461         }
 462 
 463         @Override
 464         boolean viewAsTypeChecks(MethodType newType, boolean strict) {
 465             super.viewAsTypeChecks(newType, true);
 466             if (strict) return true;
 467             // extra assertion for non-strict checks:
 468             assert (type().lastParameterType().getComponentType()
 469                     .isAssignableFrom(
 470                             newType.lastParameterType().getComponentType()))
 471                     : Arrays.asList(this, newType);
 472             return true;
 473         }
 474     }
 475 
 476     /** Factory method:  Spread selected argument. */
 477     static MethodHandle makeSpreadArguments(MethodHandle target,
 478                                             Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
 479         MethodType targetType = target.type();
 480 
 481         for (int i = 0; i < spreadArgCount; i++) {
 482             Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i);
 483             if (arg == null)  arg = Object.class;
 484             targetType = targetType.changeParameterType(spreadArgPos + i, arg);
 485         }
 486         target = target.asType(targetType);
 487 
 488         MethodType srcType = targetType
 489                 .replaceParameterTypes(spreadArgPos, spreadArgPos + spreadArgCount, spreadArgType);
 490         // Now build a LambdaForm.
 491         MethodType lambdaType = srcType.invokerType();
 492         Name[] names = arguments(spreadArgCount + 2, lambdaType);
 493         int nameCursor = lambdaType.parameterCount();
 494         int[] indexes = new int[targetType.parameterCount()];
 495 
 496         for (int i = 0, argIndex = 1; i < targetType.parameterCount() + 1; i++, argIndex++) {
 497             Class<?> src = lambdaType.parameterType(i);
 498             if (i == spreadArgPos) {
 499                 // Spread the array.
 500                 MethodHandle aload = MethodHandles.arrayElementGetter(spreadArgType);
 501                 Name array = names[argIndex];
 502                 names[nameCursor++] = new Name(Lazy.NF_checkSpreadArgument, array, spreadArgCount);
 503                 for (int j = 0; j < spreadArgCount; i++, j++) {
 504                     indexes[i] = nameCursor;
 505                     names[nameCursor++] = new Name(aload, array, j);
 506                 }
 507             } else if (i < indexes.length) {
 508                 indexes[i] = argIndex;
 509             }
 510         }
 511         assert(nameCursor == names.length-1);  // leave room for the final call
 512 
 513         // Build argument array for the call.
 514         Name[] targetArgs = new Name[targetType.parameterCount()];
 515         for (int i = 0; i < targetType.parameterCount(); i++) {
 516             int idx = indexes[i];
 517             targetArgs[i] = names[idx];
 518         }
 519         names[names.length - 1] = new Name(target, (Object[]) targetArgs);
 520 
 521         LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names);
 522         return SimpleMethodHandle.make(srcType, form);
 523     }
 524 
 525     static void checkSpreadArgument(Object av, int n) {
 526         if (av == null) {
 527             if (n == 0)  return;
 528         } else if (av instanceof Object[]) {
 529             int len = ((Object[])av).length;
 530             if (len == n)  return;
 531         } else {
 532             int len = java.lang.reflect.Array.getLength(av);
 533             if (len == n)  return;
 534         }
 535         // fall through to error:
 536         throw newIllegalArgumentException("array is not of length "+n);
 537     }
 538 
 539     /**
 540      * Pre-initialized NamedFunctions for bootstrapping purposes.
 541      * Factored in an inner class to delay initialization until first usage.
 542      */
 543     private static class Lazy {
 544         private static final Class<?> MHI = MethodHandleImpl.class;
 545 
 546         static final NamedFunction NF_checkSpreadArgument;
 547         static final NamedFunction NF_guardWithCatch;
 548         static final NamedFunction NF_throwException;
 549 
 550         static final MethodHandle MH_castReference;
 551         static final MethodHandle MH_selectAlternative;
 552         static final MethodHandle MH_copyAsPrimitiveArray;
 553         static final MethodHandle MH_fillNewTypedArray;
 554         static final MethodHandle MH_fillNewArray;
 555         static final MethodHandle MH_arrayIdentity;
 556 
 557         static {
 558             try {
 559                 NF_checkSpreadArgument = new NamedFunction(MHI.getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
 560                 NF_guardWithCatch      = new NamedFunction(MHI.getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class,
 561                                                                                  MethodHandle.class, Object[].class));
 562                 NF_throwException      = new NamedFunction(MHI.getDeclaredMethod("throwException", Throwable.class));
 563 
 564                 NF_checkSpreadArgument.resolve();
 565                 NF_guardWithCatch.resolve();
 566                 NF_throwException.resolve();
 567 
 568                 MH_castReference        = IMPL_LOOKUP.findStatic(MHI, "castReference",
 569                                             MethodType.methodType(Object.class, Class.class, Object.class));
 570                 MH_copyAsPrimitiveArray = IMPL_LOOKUP.findStatic(MHI, "copyAsPrimitiveArray",
 571                                             MethodType.methodType(Object.class, Wrapper.class, Object[].class));
 572                 MH_arrayIdentity        = IMPL_LOOKUP.findStatic(MHI, "identity",
 573                                             MethodType.methodType(Object[].class, Object[].class));
 574                 MH_fillNewArray         = IMPL_LOOKUP.findStatic(MHI, "fillNewArray",
 575                                             MethodType.methodType(Object[].class, Integer.class, Object[].class));
 576                 MH_fillNewTypedArray    = IMPL_LOOKUP.findStatic(MHI, "fillNewTypedArray",
 577                                             MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class));
 578 
 579                 MH_selectAlternative    = makeIntrinsic(
 580                         IMPL_LOOKUP.findStatic(MHI, "selectAlternative",
 581                                 MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class)),
 582                         Intrinsic.SELECT_ALTERNATIVE);
 583             } catch (ReflectiveOperationException ex) {
 584                 throw newInternalError(ex);
 585             }
 586         }
 587     }
 588 
 589     /** Factory method:  Collect or filter selected argument(s). */
 590     static MethodHandle makeCollectArguments(MethodHandle target,
 591                 MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) {
 592         MethodType targetType = target.type();          // (a..., c, [b...])=>r
 593         MethodType collectorType = collector.type();    // (b...)=>c
 594         int collectArgCount = collectorType.parameterCount();
 595         Class<?> collectValType = collectorType.returnType();
 596         int collectValCount = (collectValType == void.class ? 0 : 1);
 597         MethodType srcType = targetType                 // (a..., [b...])=>r
 598                 .dropParameterTypes(collectArgPos, collectArgPos+collectValCount);
 599         if (!retainOriginalArgs) {                      // (a..., b...)=>r
 600             srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList());
 601         }
 602         // in  arglist: [0: ...keep1 | cpos: collect...  | cpos+cacount: keep2... ]
 603         // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ]
 604         // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ]
 605 
 606         // Now build a LambdaForm.
 607         MethodType lambdaType = srcType.invokerType();
 608         Name[] names = arguments(2, lambdaType);
 609         final int collectNamePos = names.length - 2;
 610         final int targetNamePos  = names.length - 1;
 611 
 612         Name[] collectorArgs = Arrays.copyOfRange(names, 1 + collectArgPos, 1 + collectArgPos + collectArgCount);
 613         names[collectNamePos] = new Name(collector, (Object[]) collectorArgs);
 614 
 615         // Build argument array for the target.
 616         // Incoming LF args to copy are: [ (mh) headArgs collectArgs tailArgs ].
 617         // Output argument array is [ headArgs (collectVal)? (collectArgs)? tailArgs ].
 618         Name[] targetArgs = new Name[targetType.parameterCount()];
 619         int inputArgPos  = 1;  // incoming LF args to copy to target
 620         int targetArgPos = 0;  // fill pointer for targetArgs
 621         int chunk = collectArgPos;  // |headArgs|
 622         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 623         inputArgPos  += chunk;
 624         targetArgPos += chunk;
 625         if (collectValType != void.class) {
 626             targetArgs[targetArgPos++] = names[collectNamePos];
 627         }
 628         chunk = collectArgCount;
 629         if (retainOriginalArgs) {
 630             System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 631             targetArgPos += chunk;   // optionally pass on the collected chunk
 632         }
 633         inputArgPos += chunk;
 634         chunk = targetArgs.length - targetArgPos;  // all the rest
 635         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 636         assert(inputArgPos + chunk == collectNamePos);  // use of rest of input args also
 637         names[targetNamePos] = new Name(target, (Object[]) targetArgs);
 638 
 639         LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names);
 640         return SimpleMethodHandle.make(srcType, form);
 641     }
 642 
 643     @LambdaForm.Hidden
 644     static
 645     MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
 646         return testResult ? target : fallback;
 647     }
 648 
 649     static
 650     MethodHandle makeGuardWithTest(MethodHandle test,
 651                                    MethodHandle target,
 652                                    MethodHandle fallback) {
 653         MethodType basicType = target.type().basicType();
 654         MethodHandle invokeBasic = MethodHandles.basicInvoker(basicType);
 655         int arity = basicType.parameterCount();
 656         int extraNames = 3;
 657         MethodType lambdaType = basicType.invokerType();
 658         Name[] names = arguments(extraNames, lambdaType);
 659 
 660         Object[] testArgs   = Arrays.copyOfRange(names, 1, 1 + arity, Object[].class);
 661         Object[] targetArgs = Arrays.copyOfRange(names, 0, 1 + arity, Object[].class);
 662 
 663         // call test
 664         names[arity + 1] = new Name(test, testArgs);
 665 
 666         // call selectAlternative
 667         Object[] selectArgs = { names[arity + 1], target, fallback };
 668         names[arity + 2] = new Name(Lazy.MH_selectAlternative, selectArgs);
 669         targetArgs[0] = names[arity + 2];
 670 
 671         // call target or fallback
 672         names[arity + 3] = new Name(new NamedFunction(invokeBasic), targetArgs);
 673 
 674         LambdaForm form = new LambdaForm("guard", lambdaType.parameterCount(), names);
 675         return SimpleMethodHandle.make(target.type(), form);
 676     }
 677 
 678     /**
 679      * The LambaForm shape for catchException combinator is the following:
 680      * <blockquote><pre>{@code
 681      *  guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{
 682      *    t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L);
 683      *    t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L);
 684      *    t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L);
 685      *    t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L);
 686      *    t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L);
 687      *    t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L);
 688      *    t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L);
 689      *   t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I}
 690      * }</pre></blockquote>
 691      *
 692      * argL0 and argL2 are target and catcher method handles. argL1 is exception class.
 693      * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[]
 694      * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()).
 695      *
 696      * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms
 697      * among catchException combinators with the same basic type.
 698      */
 699     private static LambdaForm makeGuardWithCatchForm(MethodType basicType) {
 700         MethodType lambdaType = basicType.invokerType();
 701 
 702         LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC);
 703         if (lform != null) {
 704             return lform;
 705         }
 706         final int THIS_MH      = 0;  // the BMH_LLLLL
 707         final int ARG_BASE     = 1;  // start of incoming arguments
 708         final int ARG_LIMIT    = ARG_BASE + basicType.parameterCount();
 709 
 710         int nameCursor = ARG_LIMIT;
 711         final int GET_TARGET       = nameCursor++;
 712         final int GET_CLASS        = nameCursor++;
 713         final int GET_CATCHER      = nameCursor++;
 714         final int GET_COLLECT_ARGS = nameCursor++;
 715         final int GET_UNBOX_RESULT = nameCursor++;
 716         final int BOXED_ARGS       = nameCursor++;
 717         final int TRY_CATCH        = nameCursor++;
 718         final int UNBOX_RESULT     = nameCursor++;
 719 
 720         Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType);
 721 
 722         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 723         names[GET_TARGET]       = new Name(data.getterFunction(0), names[THIS_MH]);
 724         names[GET_CLASS]        = new Name(data.getterFunction(1), names[THIS_MH]);
 725         names[GET_CATCHER]      = new Name(data.getterFunction(2), names[THIS_MH]);
 726         names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]);
 727         names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]);
 728 
 729         // FIXME: rework argument boxing/result unboxing logic for LF interpretation
 730 
 731         // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...);
 732         MethodType collectArgsType = basicType.changeReturnType(Object.class);
 733         MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType);
 734         Object[] args = new Object[invokeBasic.type().parameterCount()];
 735         args[0] = names[GET_COLLECT_ARGS];
 736         System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE);
 737         names[BOXED_ARGS] = new Name(makeIntrinsic(invokeBasic, Intrinsic.GUARD_WITH_CATCH), args);
 738 
 739         // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L);
 740         Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]};
 741         names[TRY_CATCH] = new Name(Lazy.NF_guardWithCatch, gwcArgs);
 742 
 743         // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L);
 744         MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class));
 745         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]};
 746         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
 747 
 748         lform = new LambdaForm("guardWithCatch", lambdaType.parameterCount(), names);
 749 
 750         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform);
 751     }
 752 
 753     static
 754     MethodHandle makeGuardWithCatch(MethodHandle target,
 755                                     Class<? extends Throwable> exType,
 756                                     MethodHandle catcher) {
 757         MethodType type = target.type();
 758         LambdaForm form = makeGuardWithCatchForm(type.basicType());
 759 
 760         // Prepare auxiliary method handles used during LambdaForm interpreation.
 761         // Box arguments and wrap them into Object[]: ValueConversions.array().
 762         MethodType varargsType = type.changeReturnType(Object[].class);
 763         MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType);
 764         // Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore().
 765         MethodHandle unboxResult;
 766         Class<?> rtype = type.returnType();
 767         if (rtype.isPrimitive()) {
 768             if (rtype == void.class) {
 769                 unboxResult = ValueConversions.ignore();
 770             } else {
 771                 Wrapper w = Wrapper.forPrimitiveType(type.returnType());
 772                 unboxResult = ValueConversions.unboxExact(w);
 773             }
 774         } else {
 775             unboxResult = MethodHandles.identity(Object.class);
 776         }
 777 
 778         BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL();
 779         BoundMethodHandle mh;
 780         try {
 781             mh = (BoundMethodHandle)
 782                     data.constructor().invokeBasic(type, form, (Object) target, (Object) exType, (Object) catcher,
 783                                                    (Object) collectArgs, (Object) unboxResult);
 784         } catch (Throwable ex) {
 785             throw uncaughtException(ex);
 786         }
 787         assert(mh.type() == type);
 788         return mh;
 789     }
 790 
 791     /**
 792      * Intrinsified during LambdaForm compilation
 793      * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}).
 794      */
 795     @LambdaForm.Hidden
 796     static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher,
 797                                  Object... av) throws Throwable {
 798         // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case.
 799         try {
 800             return target.asFixedArity().invokeWithArguments(av);
 801         } catch (Throwable t) {
 802             if (!exType.isInstance(t)) throw t;
 803             return catcher.asFixedArity().invokeWithArguments(prepend(t, av));
 804         }
 805     }
 806 
 807     /** Prepend an element {@code elem} to an {@code array}. */
 808     @LambdaForm.Hidden
 809     private static Object[] prepend(Object elem, Object[] array) {
 810         Object[] newArray = new Object[array.length+1];
 811         newArray[0] = elem;
 812         System.arraycopy(array, 0, newArray, 1, array.length);
 813         return newArray;
 814     }
 815 
 816     static
 817     MethodHandle throwException(MethodType type) {
 818         assert(Throwable.class.isAssignableFrom(type.parameterType(0)));
 819         int arity = type.parameterCount();
 820         if (arity > 1) {
 821             MethodHandle mh = throwException(type.dropParameterTypes(1, arity));
 822             mh = MethodHandles.dropArguments(mh, 1, type.parameterList().subList(1, arity));
 823             return mh;
 824         }
 825         return makePairwiseConvert(Lazy.NF_throwException.resolvedHandle(), type, false, true);
 826     }
 827 
 828     static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
 829 
 830     static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2];
 831     static MethodHandle fakeMethodHandleInvoke(MemberName method) {
 832         int idx;
 833         assert(method.isMethodHandleInvoke());
 834         switch (method.getName()) {
 835         case "invoke":       idx = 0; break;
 836         case "invokeExact":  idx = 1; break;
 837         default:             throw new InternalError(method.getName());
 838         }
 839         MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx];
 840         if (mh != null)  return mh;
 841         MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class,
 842                                                 MethodHandle.class, Object[].class);
 843         mh = throwException(type);
 844         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle"));
 845         if (!method.getInvocationType().equals(mh.type()))
 846             throw new InternalError(method.toString());
 847         mh = mh.withInternalMemberName(method, false);
 848         mh = mh.asVarargsCollector(Object[].class);
 849         assert(method.isVarargs());
 850         FAKE_METHOD_HANDLE_INVOKE[idx] = mh;
 851         return mh;
 852     }
 853 
 854     /**
 855      * Create an alias for the method handle which, when called,
 856      * appears to be called from the same class loader and protection domain
 857      * as hostClass.
 858      * This is an expensive no-op unless the method which is called
 859      * is sensitive to its caller.  A small number of system methods
 860      * are in this category, including Class.forName and Method.invoke.
 861      */
 862     static
 863     MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 864         return BindCaller.bindCaller(mh, hostClass);
 865     }
 866 
 867     // Put the whole mess into its own nested class.
 868     // That way we can lazily load the code and set up the constants.
 869     private static class BindCaller {
 870         static
 871         MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 872             // Do not use this function to inject calls into system classes.
 873             if (hostClass == null
 874                 ||    (hostClass.isArray() ||
 875                        hostClass.isPrimitive() ||
 876                        hostClass.getName().startsWith("java.") ||
 877                        hostClass.getName().startsWith("sun."))) {
 878                 throw new InternalError();  // does not happen, and should not anyway
 879             }
 880             // For simplicity, convert mh to a varargs-like method.
 881             MethodHandle vamh = prepareForInvoker(mh);
 882             // Cache the result of makeInjectedInvoker once per argument class.
 883             MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
 884             return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass);
 885         }
 886 
 887         private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
 888             Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
 889             if (hostClass.getClassLoader() != bcc.getClassLoader())
 890                 throw new InternalError(hostClass.getName()+" (CL)");
 891             try {
 892                 if (hostClass.getProtectionDomain() != bcc.getProtectionDomain())
 893                     throw new InternalError(hostClass.getName()+" (PD)");
 894             } catch (SecurityException ex) {
 895                 // Self-check was blocked by security manager.  This is OK.
 896                 // In fact the whole try body could be turned into an assertion.
 897             }
 898             try {
 899                 MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class));
 900                 init.invokeExact();  // force initialization of the class
 901             } catch (Throwable ex) {
 902                 throw uncaughtException(ex);
 903             }
 904             MethodHandle bccInvoker;
 905             try {
 906                 MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
 907                 bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT);
 908             } catch (ReflectiveOperationException ex) {
 909                 throw uncaughtException(ex);
 910             }
 911             // Test the invoker, to ensure that it really injects into the right place.
 912             try {
 913                 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
 914                 Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc});
 915             } catch (Throwable ex) {
 916                 throw new InternalError(ex);
 917             }
 918             return bccInvoker;
 919         }
 920         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
 921             @Override protected MethodHandle computeValue(Class<?> hostClass) {
 922                 return makeInjectedInvoker(hostClass);
 923             }
 924         };
 925 
 926         // Adapt mh so that it can be called directly from an injected invoker:
 927         private static MethodHandle prepareForInvoker(MethodHandle mh) {
 928             mh = mh.asFixedArity();
 929             MethodType mt = mh.type();
 930             int arity = mt.parameterCount();
 931             MethodHandle vamh = mh.asType(mt.generic());
 932             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 933             vamh = vamh.asSpreader(Object[].class, arity);
 934             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 935             return vamh;
 936         }
 937 
 938         // Undo the adapter effect of prepareForInvoker:
 939         private static MethodHandle restoreToType(MethodHandle vamh,
 940                                                   MethodHandle original,
 941                                                   Class<?> hostClass) {
 942             MethodType type = original.type();
 943             MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount());
 944             MemberName member = original.internalMemberName();
 945             mh = mh.asType(type);
 946             mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass);
 947             return mh;
 948         }
 949 
 950         private static final MethodHandle MH_checkCallerClass;
 951         static {
 952             final Class<?> THIS_CLASS = BindCaller.class;
 953             assert(checkCallerClass(THIS_CLASS, THIS_CLASS));
 954             try {
 955                 MH_checkCallerClass = IMPL_LOOKUP
 956                     .findStatic(THIS_CLASS, "checkCallerClass",
 957                                 MethodType.methodType(boolean.class, Class.class, Class.class));
 958                 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS));
 959             } catch (Throwable ex) {
 960                 throw new InternalError(ex);
 961             }
 962         }
 963 
 964         @CallerSensitive
 965         private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
 966             // This method is called via MH_checkCallerClass and so it's
 967             // correct to ask for the immediate caller here.
 968             Class<?> actual = Reflection.getCallerClass();
 969             if (actual != expected && actual != expected2)
 970                 throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
 971                                         +(expected == expected2 ? "" : ", or else "+expected2.getName()));
 972             return true;
 973         }
 974 
 975         private static final byte[] T_BYTES;
 976         static {
 977             final Object[] values = {null};
 978             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 979                     public Void run() {
 980                         try {
 981                             Class<T> tClass = T.class;
 982                             String tName = tClass.getName();
 983                             String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class";
 984                             java.net.URLConnection uconn = tClass.getResource(tResource).openConnection();
 985                             int len = uconn.getContentLength();
 986                             byte[] bytes = new byte[len];
 987                             try (java.io.InputStream str = uconn.getInputStream()) {
 988                                 int nr = str.read(bytes);
 989                                 if (nr != len)  throw new java.io.IOException(tResource);
 990                             }
 991                             values[0] = bytes;
 992                         } catch (java.io.IOException ex) {
 993                             throw new InternalError(ex);
 994                         }
 995                         return null;
 996                     }
 997                 });
 998             T_BYTES = (byte[]) values[0];
 999         }
1000 
1001         // The following class is used as a template for Unsafe.defineAnonymousClass:
1002         private static class T {
1003             static void init() { }  // side effect: initializes this class
1004             static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
1005                 return vamh.invokeExact(args);
1006             }
1007         }
1008     }
1009 
1010 
1011     /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */
1012     private static final class WrappedMember extends DelegatingMethodHandle {
1013         private final MethodHandle target;
1014         private final MemberName member;
1015         private final Class<?> callerClass;
1016         private final boolean isInvokeSpecial;
1017 
1018         private WrappedMember(MethodHandle target, MethodType type,
1019                               MemberName member, boolean isInvokeSpecial,
1020                               Class<?> callerClass) {
1021             super(type, target);
1022             this.target = target;
1023             this.member = member;
1024             this.callerClass = callerClass;
1025             this.isInvokeSpecial = isInvokeSpecial;
1026         }
1027 
1028         @Override
1029         MemberName internalMemberName() {
1030             return member;
1031         }
1032         @Override
1033         Class<?> internalCallerClass() {
1034             return callerClass;
1035         }
1036         @Override
1037         boolean isInvokeSpecial() {
1038             return isInvokeSpecial;
1039         }
1040         @Override
1041         protected MethodHandle getTarget() {
1042             return target;
1043         }
1044         @Override
1045         public MethodHandle asTypeUncached(MethodType newType) {
1046             // This MH is an alias for target, except for the MemberName
1047             // Drop the MemberName if there is any conversion.
1048             return asTypeCache = target.asType(newType);
1049         }
1050     }
1051 
1052     static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) {
1053         if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial())
1054             return target;
1055         return new WrappedMember(target, target.type(), member, isInvokeSpecial, null);
1056     }
1057 
1058     /** Intrinsic IDs */
1059     /*non-public*/
1060     enum Intrinsic {
1061         SELECT_ALTERNATIVE,
1062         GUARD_WITH_CATCH,
1063         NEW_ARRAY,
1064         ARRAY_LOAD,
1065         ARRAY_STORE,
1066         NONE // no intrinsic associated
1067     }
1068 
1069     /** Mark arbitrary method handle as intrinsic.
1070      * InvokerBytecodeGenerator uses this info to produce more efficient bytecode shape. */
1071     private static final class IntrinsicMethodHandle extends DelegatingMethodHandle {
1072         private final MethodHandle target;
1073         private final Intrinsic intrinsicName;
1074 
1075         IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName) {
1076             super(target.type(), target);
1077             this.target = target;
1078             this.intrinsicName = intrinsicName;
1079         }
1080 
1081         @Override
1082         protected MethodHandle getTarget() {
1083             return target;
1084         }
1085 
1086         @Override
1087         Intrinsic intrinsicName() {
1088             return intrinsicName;
1089         }
1090 
1091         @Override
1092         public MethodHandle asTypeUncached(MethodType newType) {
1093             // This MH is an alias for target, except for the intrinsic name
1094             // Drop the name if there is any conversion.
1095             return asTypeCache = target.asType(newType);
1096         }
1097 
1098         @Override
1099         String internalProperties() {
1100             return super.internalProperties() +
1101                     "\n& Intrinsic="+intrinsicName;
1102         }
1103     }
1104 
1105     static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName) {
1106         if (intrinsicName == target.intrinsicName())
1107             return target;
1108         return new IntrinsicMethodHandle(target, intrinsicName);
1109     }
1110 
1111     static MethodHandle makeIntrinsic(MethodType type, LambdaForm form, Intrinsic intrinsicName) {
1112         return new IntrinsicMethodHandle(SimpleMethodHandle.make(type, form), intrinsicName);
1113     }
1114 
1115     /// Collection of multiple arguments.
1116 
1117     private static MethodHandle findCollector(String name, int nargs, Class<?> rtype, Class<?>... ptypes) {
1118         MethodType type = MethodType.genericMethodType(nargs)
1119                 .changeReturnType(rtype)
1120                 .insertParameterTypes(0, ptypes);
1121         try {
1122             return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, name, type);
1123         } catch (ReflectiveOperationException ex) {
1124             return null;
1125         }
1126     }
1127 
1128     private static final Object[] NO_ARGS_ARRAY = {};
1129     private static Object[] makeArray(Object... args) { return args; }
1130     private static Object[] array() { return NO_ARGS_ARRAY; }
1131     private static Object[] array(Object a0)
1132                 { return makeArray(a0); }
1133     private static Object[] array(Object a0, Object a1)
1134                 { return makeArray(a0, a1); }
1135     private static Object[] array(Object a0, Object a1, Object a2)
1136                 { return makeArray(a0, a1, a2); }
1137     private static Object[] array(Object a0, Object a1, Object a2, Object a3)
1138                 { return makeArray(a0, a1, a2, a3); }
1139     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1140                                   Object a4)
1141                 { return makeArray(a0, a1, a2, a3, a4); }
1142     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1143                                   Object a4, Object a5)
1144                 { return makeArray(a0, a1, a2, a3, a4, a5); }
1145     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1146                                   Object a4, Object a5, Object a6)
1147                 { return makeArray(a0, a1, a2, a3, a4, a5, a6); }
1148     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1149                                   Object a4, Object a5, Object a6, Object a7)
1150                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); }
1151     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1152                                   Object a4, Object a5, Object a6, Object a7,
1153                                   Object a8)
1154                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); }
1155     private static Object[] array(Object a0, Object a1, Object a2, Object a3,
1156                                   Object a4, Object a5, Object a6, Object a7,
1157                                   Object a8, Object a9)
1158                 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }
1159     private static MethodHandle[] makeArrays() {
1160         ArrayList<MethodHandle> mhs = new ArrayList<>();
1161         for (;;) {
1162             MethodHandle mh = findCollector("array", mhs.size(), Object[].class);
1163             if (mh == null)  break;
1164             mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1165             mhs.add(mh);
1166         }
1167         assert(mhs.size() == 11);  // current number of methods
1168         return mhs.toArray(new MethodHandle[MAX_ARITY+1]);
1169     }
1170     private static final MethodHandle[] ARRAYS = makeArrays();
1171 
1172     // filling versions of the above:
1173     // using Integer len instead of int len and no varargs to avoid bootstrapping problems
1174     private static Object[] fillNewArray(Integer len, Object[] /*not ...*/ args) {
1175         Object[] a = new Object[len];
1176         fillWithArguments(a, 0, args);
1177         return a;
1178     }
1179     private static Object[] fillNewTypedArray(Object[] example, Integer len, Object[] /*not ...*/ args) {
1180         Object[] a = Arrays.copyOf(example, len);
1181         assert(a.getClass() != Object[].class);
1182         fillWithArguments(a, 0, args);
1183         return a;
1184     }
1185     private static void fillWithArguments(Object[] a, int pos, Object... args) {
1186         System.arraycopy(args, 0, a, pos, args.length);
1187     }
1188     // using Integer pos instead of int pos to avoid bootstrapping problems
1189     private static Object[] fillArray(Integer pos, Object[] a, Object a0)
1190                 { fillWithArguments(a, pos, a0); return a; }
1191     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1)
1192                 { fillWithArguments(a, pos, a0, a1); return a; }
1193     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2)
1194                 { fillWithArguments(a, pos, a0, a1, a2); return a; }
1195     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3)
1196                 { fillWithArguments(a, pos, a0, a1, a2, a3); return a; }
1197     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1198                                   Object a4)
1199                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4); return a; }
1200     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1201                                   Object a4, Object a5)
1202                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5); return a; }
1203     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1204                                   Object a4, Object a5, Object a6)
1205                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6); return a; }
1206     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1207                                   Object a4, Object a5, Object a6, Object a7)
1208                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7); return a; }
1209     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1210                                   Object a4, Object a5, Object a6, Object a7,
1211                                   Object a8)
1212                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8); return a; }
1213     private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3,
1214                                   Object a4, Object a5, Object a6, Object a7,
1215                                   Object a8, Object a9)
1216                 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; }
1217     private static MethodHandle[] makeFillArrays() {
1218         ArrayList<MethodHandle> mhs = new ArrayList<>();
1219         mhs.add(null);  // there is no empty fill; at least a0 is required
1220         for (;;) {
1221             MethodHandle mh = findCollector("fillArray", mhs.size(), Object[].class, Integer.class, Object[].class);
1222             if (mh == null)  break;
1223             mhs.add(mh);
1224         }
1225         assert(mhs.size() == 11);  // current number of methods
1226         return mhs.toArray(new MethodHandle[0]);
1227     }
1228     private static final MethodHandle[] FILL_ARRAYS = makeFillArrays();
1229 
1230     private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) {
1231         Object a = w.makeArray(boxes.length);
1232         w.copyArrayUnboxing(boxes, 0, a, 0, boxes.length);
1233         return a;
1234     }
1235 
1236     /** Return a method handle that takes the indicated number of Object
1237      *  arguments and returns an Object array of them, as if for varargs.
1238      */
1239     static MethodHandle varargsArray(int nargs) {
1240         MethodHandle mh = ARRAYS[nargs];
1241         if (mh != null)  return mh;
1242         mh = findCollector("array", nargs, Object[].class);
1243         if (mh != null)  mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1244         if (mh != null)  return ARRAYS[nargs] = mh;
1245         mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs);
1246         assert(assertCorrectArity(mh, nargs));
1247         mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1248         return ARRAYS[nargs] = mh;
1249     }
1250 
1251     private static boolean assertCorrectArity(MethodHandle mh, int arity) {
1252         assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh;
1253         return true;
1254     }
1255 
1256     // Array identity function (used as Lazy.MH_arrayIdentity).
1257     static <T> T[] identity(T[] x) {
1258         return x;
1259     }
1260 
1261     private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) {
1262         // Build up the result mh as a sequence of fills like this:
1263         //   finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23))
1264         // The various fill(_,10*I,___*[J]) are reusable.
1265         int leftLen = Math.min(nargs, LEFT_ARGS);  // absorb some arguments immediately
1266         int rightLen = nargs - leftLen;
1267         MethodHandle leftCollector = newArray.bindTo(nargs);
1268         leftCollector = leftCollector.asCollector(Object[].class, leftLen);
1269         MethodHandle mh = finisher;
1270         if (rightLen > 0) {
1271             MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen);
1272             if (mh == Lazy.MH_arrayIdentity)
1273                 mh = rightFiller;
1274             else
1275                 mh = MethodHandles.collectArguments(mh, 0, rightFiller);
1276         }
1277         if (mh == Lazy.MH_arrayIdentity)
1278             mh = leftCollector;
1279         else
1280             mh = MethodHandles.collectArguments(mh, 0, leftCollector);
1281         return mh;
1282     }
1283 
1284     private static final int LEFT_ARGS = (FILL_ARRAYS.length - 1);
1285     private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1];
1286     /** fill_array_to_right(N).invoke(a, argL..arg[N-1])
1287      *  fills a[L]..a[N-1] with corresponding arguments,
1288      *  and then returns a.  The value L is a global constant (LEFT_ARGS).
1289      */
1290     private static MethodHandle fillToRight(int nargs) {
1291         MethodHandle filler = FILL_ARRAY_TO_RIGHT[nargs];
1292         if (filler != null)  return filler;
1293         filler = buildFiller(nargs);
1294         assert(assertCorrectArity(filler, nargs - LEFT_ARGS + 1));
1295         return FILL_ARRAY_TO_RIGHT[nargs] = filler;
1296     }
1297     private static MethodHandle buildFiller(int nargs) {
1298         if (nargs <= LEFT_ARGS)
1299             return Lazy.MH_arrayIdentity;  // no args to fill; return the array unchanged
1300         // we need room for both mh and a in mh.invoke(a, arg*[nargs])
1301         final int CHUNK = LEFT_ARGS;
1302         int rightLen = nargs % CHUNK;
1303         int midLen = nargs - rightLen;
1304         if (rightLen == 0) {
1305             midLen = nargs - (rightLen = CHUNK);
1306             if (FILL_ARRAY_TO_RIGHT[midLen] == null) {
1307                 // build some precursors from left to right
1308                 for (int j = LEFT_ARGS % CHUNK; j < midLen; j += CHUNK)
1309                     if (j > LEFT_ARGS)  fillToRight(j);
1310             }
1311         }
1312         if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS);
1313         assert(rightLen > 0);
1314         MethodHandle midFill = fillToRight(midLen);  // recursive fill
1315         MethodHandle rightFill = FILL_ARRAYS[rightLen].bindTo(midLen);  // [midLen..nargs-1]
1316         assert(midFill.type().parameterCount()   == 1 + midLen - LEFT_ARGS);
1317         assert(rightFill.type().parameterCount() == 1 + rightLen);
1318 
1319         // Combine the two fills:
1320         //   right(mid(a, x10..x19), x20..x23)
1321         // The final product will look like this:
1322         //   right(mid(newArrayLeft(24, x0..x9), x10..x19), x20..x23)
1323         if (midLen == LEFT_ARGS)
1324             return rightFill;
1325         else
1326             return MethodHandles.collectArguments(rightFill, 0, midFill);
1327     }
1328 
1329     // Type-polymorphic version of varargs maker.
1330     private static final ClassValue<MethodHandle[]> TYPED_COLLECTORS
1331         = new ClassValue<MethodHandle[]>() {
1332             @Override
1333             protected MethodHandle[] computeValue(Class<?> type) {
1334                 return new MethodHandle[256];
1335             }
1336     };
1337 
1338     static final int MAX_JVM_ARITY = 255;  // limit imposed by the JVM
1339 
1340     /** Return a method handle that takes the indicated number of
1341      *  typed arguments and returns an array of them.
1342      *  The type argument is the array type.
1343      */
1344     static MethodHandle varargsArray(Class<?> arrayType, int nargs) {
1345         Class<?> elemType = arrayType.getComponentType();
1346         if (elemType == null)  throw new IllegalArgumentException("not an array: "+arrayType);
1347         // FIXME: Need more special casing and caching here.
1348         if (nargs >= MAX_JVM_ARITY/2 - 1) {
1349             int slots = nargs;
1350             final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1;  // 1 for receiver MH
1351             if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive())
1352                 slots *= Wrapper.forPrimitiveType(elemType).stackSlots();
1353             if (slots > MAX_ARRAY_SLOTS)
1354                 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs);
1355         }
1356         if (elemType == Object.class)
1357             return varargsArray(nargs);
1358         // other cases:  primitive arrays, subtypes of Object[]
1359         MethodHandle cache[] = TYPED_COLLECTORS.get(elemType);
1360         MethodHandle mh = nargs < cache.length ? cache[nargs] : null;
1361         if (mh != null)  return mh;
1362         if (nargs == 0) {
1363             Object example = java.lang.reflect.Array.newInstance(arrayType.getComponentType(), 0);
1364             mh = MethodHandles.constant(arrayType, example);
1365         } else if (elemType.isPrimitive()) {
1366             MethodHandle builder = Lazy.MH_fillNewArray;
1367             MethodHandle producer = buildArrayProducer(arrayType);
1368             mh = buildVarargsArray(builder, producer, nargs);
1369         } else {
1370             Class<? extends Object[]> objArrayType = arrayType.asSubclass(Object[].class);
1371             Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType);
1372             MethodHandle builder = Lazy.MH_fillNewTypedArray.bindTo(example);
1373             MethodHandle producer = Lazy.MH_arrayIdentity; // must be weakly typed
1374             mh = buildVarargsArray(builder, producer, nargs);
1375         }
1376         mh = mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType)));
1377         mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY);
1378         assert(assertCorrectArity(mh, nargs));
1379         if (nargs < cache.length)
1380             cache[nargs] = mh;
1381         return mh;
1382     }
1383 
1384     private static MethodHandle buildArrayProducer(Class<?> arrayType) {
1385         Class<?> elemType = arrayType.getComponentType();
1386         assert(elemType.isPrimitive());
1387         return Lazy.MH_copyAsPrimitiveArray.bindTo(Wrapper.forPrimitiveType(elemType));
1388     }
1389 }