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