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.HashMap;
  33 import sun.invoke.empty.Empty;
  34 import sun.invoke.util.ValueConversions;
  35 import sun.invoke.util.VerifyType;
  36 import sun.invoke.util.Wrapper;
  37 import sun.reflect.CallerSensitive;
  38 import sun.reflect.Reflection;
  39 import static java.lang.invoke.LambdaForm.*;
  40 import static java.lang.invoke.MethodHandleStatics.*;
  41 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  42 
  43 /**
  44  * Trusted implementation code for MethodHandle.
  45  * @author jrose
  46  */
  47 /*non-public*/ abstract class MethodHandleImpl {
  48     /// Factory methods to create method handles:
  49 
  50     static void initStatics() {
  51         // Trigger selected static initializations.
  52         MemberName.Factory.INSTANCE.getClass();
  53     }
  54 
  55     static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, boolean isSetter) {
  56         if (!arrayClass.isArray())
  57             throw newIllegalArgumentException("not an array: "+arrayClass);
  58         MethodHandle accessor = ArrayAccessor.getAccessor(arrayClass, isSetter);
  59         MethodType srcType = accessor.type().erase();
  60         MethodType lambdaType = srcType.invokerType();
  61         Name[] names = arguments(1, lambdaType);
  62         Name[] args  = Arrays.copyOfRange(names, 1, 1 + srcType.parameterCount());
  63         names[names.length - 1] = new Name(accessor.asType(srcType), (Object[]) args);
  64         LambdaForm form = new LambdaForm("getElement", lambdaType.parameterCount(), names);
  65         MethodHandle mh = SimpleMethodHandle.make(srcType, form);
  66         if (ArrayAccessor.needCast(arrayClass)) {
  67             mh = mh.bindTo(arrayClass);
  68         }
  69         mh = mh.asType(ArrayAccessor.correctType(arrayClass, isSetter));
  70         return mh;
  71     }
  72 
  73     static final class ArrayAccessor {
  74         /// Support for array element access
  75         static final HashMap<Class<?>, MethodHandle> GETTER_CACHE = new HashMap<>();  // TODO use it
  76         static final HashMap<Class<?>, MethodHandle> SETTER_CACHE = new HashMap<>();  // TODO use it
  77 
  78         static int     getElementI(int[]     a, int i)            { return              a[i]; }
  79         static long    getElementJ(long[]    a, int i)            { return              a[i]; }
  80         static float   getElementF(float[]   a, int i)            { return              a[i]; }
  81         static double  getElementD(double[]  a, int i)            { return              a[i]; }
  82         static boolean getElementZ(boolean[] a, int i)            { return              a[i]; }
  83         static byte    getElementB(byte[]    a, int i)            { return              a[i]; }
  84         static short   getElementS(short[]   a, int i)            { return              a[i]; }
  85         static char    getElementC(char[]    a, int i)            { return              a[i]; }
  86         static Object  getElementL(Object[]  a, int i)            { return              a[i]; }
  87 
  88         static void    setElementI(int[]     a, int i, int     x) {              a[i] = x; }
  89         static void    setElementJ(long[]    a, int i, long    x) {              a[i] = x; }
  90         static void    setElementF(float[]   a, int i, float   x) {              a[i] = x; }
  91         static void    setElementD(double[]  a, int i, double  x) {              a[i] = x; }
  92         static void    setElementZ(boolean[] a, int i, boolean x) {              a[i] = x; }
  93         static void    setElementB(byte[]    a, int i, byte    x) {              a[i] = x; }
  94         static void    setElementS(short[]   a, int i, short   x) {              a[i] = x; }
  95         static void    setElementC(char[]    a, int i, char    x) {              a[i] = x; }
  96         static void    setElementL(Object[]  a, int i, Object  x) {              a[i] = x; }
  97 
  98         static Object  getElementL(Class<?> arrayClass, Object[] a, int i)           { arrayClass.cast(a); return a[i]; }
  99         static void    setElementL(Class<?> arrayClass, Object[] a, int i, Object x) { arrayClass.cast(a); a[i] = x; }
 100 
 101         // Weakly typed wrappers of Object[] accessors:
 102         static Object  getElementL(Object    a, int i)            { return getElementL((Object[])a, i); }
 103         static void    setElementL(Object    a, int i, Object  x) {        setElementL((Object[]) a, i, x); }
 104         static Object  getElementL(Object   arrayClass, Object a, int i)             { return getElementL((Class<?>) arrayClass, (Object[])a, i); }
 105         static void    setElementL(Object   arrayClass, Object a, int i, Object x)   {        setElementL((Class<?>) arrayClass, (Object[])a, i, x); }
 106 
 107         static boolean needCast(Class<?> arrayClass) {
 108             Class<?> elemClass = arrayClass.getComponentType();
 109             return !elemClass.isPrimitive() && elemClass != Object.class;
 110         }
 111         static String name(Class<?> arrayClass, boolean isSetter) {
 112             Class<?> elemClass = arrayClass.getComponentType();
 113             if (elemClass == null)  throw new IllegalArgumentException();
 114             return (!isSetter ? "getElement" : "setElement") + Wrapper.basicTypeChar(elemClass);
 115         }
 116         static final boolean USE_WEAKLY_TYPED_ARRAY_ACCESSORS = false;  // FIXME: decide
 117         static MethodType type(Class<?> arrayClass, boolean isSetter) {
 118             Class<?> elemClass = arrayClass.getComponentType();
 119             Class<?> arrayArgClass = arrayClass;
 120             if (!elemClass.isPrimitive()) {
 121                 arrayArgClass = Object[].class;
 122                 if (USE_WEAKLY_TYPED_ARRAY_ACCESSORS)
 123                     arrayArgClass = Object.class;
 124             }
 125             if (!needCast(arrayClass)) {
 126                 return !isSetter ?
 127                     MethodType.methodType(elemClass,  arrayArgClass, int.class) :
 128                     MethodType.methodType(void.class, arrayArgClass, int.class, elemClass);
 129             } else {
 130                 Class<?> classArgClass = Class.class;
 131                 if (USE_WEAKLY_TYPED_ARRAY_ACCESSORS)
 132                     classArgClass = Object.class;
 133                 return !isSetter ?
 134                     MethodType.methodType(Object.class, classArgClass, arrayArgClass, int.class) :
 135                     MethodType.methodType(void.class,   classArgClass, arrayArgClass, int.class, Object.class);
 136             }
 137         }
 138         static MethodType correctType(Class<?> arrayClass, boolean isSetter) {
 139             Class<?> elemClass = arrayClass.getComponentType();
 140             return !isSetter ?
 141                     MethodType.methodType(elemClass,  arrayClass, int.class) :
 142                     MethodType.methodType(void.class, arrayClass, int.class, elemClass);
 143         }
 144         static MethodHandle getAccessor(Class<?> arrayClass, boolean isSetter) {
 145             String     name = name(arrayClass, isSetter);
 146             MethodType type = type(arrayClass, isSetter);
 147             try {
 148                 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type);
 149             } catch (ReflectiveOperationException ex) {
 150                 throw uncaughtException(ex);
 151             }
 152         }
 153     }
 154 
 155     /**
 156      * Create a JVM-level adapter method handle to conform the given method
 157      * handle to the similar newType, using only pairwise argument conversions.
 158      * For each argument, convert incoming argument to the exact type needed.
 159      * The argument conversions allowed are casting, boxing and unboxing,
 160      * integral widening or narrowing, and floating point widening or narrowing.
 161      * @param srcType required call type
 162      * @param target original method handle
 163      * @param level which strength of conversion is allowed
 164      * @return an adapter to the original handle with the desired new type,
 165      *          or the original target if the types are already identical
 166      *          or null if the adaptation cannot be made
 167      */
 168     static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, int level) {
 169         assert(level >= 0 && level <= 2);
 170         MethodType dstType = target.type();
 171         assert(dstType.parameterCount() == target.type().parameterCount());
 172         if (srcType == dstType)
 173             return target;
 174 
 175         // Calculate extra arguments (temporaries) required in the names array.
 176         // FIXME: Use an ArrayList<Name>.  Some arguments require more than one conversion step.
 177         final int INARG_COUNT = srcType.parameterCount();
 178         int conversions = 0;
 179         boolean[] needConv = new boolean[1+INARG_COUNT];
 180         for (int i = 0; i <= INARG_COUNT; i++) {
 181             Class<?> src = (i == INARG_COUNT) ? dstType.returnType() : srcType.parameterType(i);
 182             Class<?> dst = (i == INARG_COUNT) ? srcType.returnType() : dstType.parameterType(i);
 183             if (!VerifyType.isNullConversion(src, dst) ||
 184                 level <= 1 && dst.isInterface() && !dst.isAssignableFrom(src)) {
 185                 needConv[i] = true;
 186                 conversions++;
 187             }
 188         }
 189         boolean retConv = needConv[INARG_COUNT];
 190 
 191         final int IN_MH         = 0;
 192         final int INARG_BASE    = 1;
 193         final int INARG_LIMIT   = INARG_BASE + INARG_COUNT;
 194         final int NAME_LIMIT    = INARG_LIMIT + conversions + 1;
 195         final int RETURN_CONV   = (!retConv ? -1         : NAME_LIMIT - 1);
 196         final int OUT_CALL      = (!retConv ? NAME_LIMIT : RETURN_CONV) - 1;
 197 
 198         // Now build a LambdaForm.
 199         MethodType lambdaType = srcType.basicType().invokerType();
 200         Name[] names = arguments(NAME_LIMIT - INARG_LIMIT, lambdaType);
 201 
 202         // Collect the arguments to the outgoing call, maybe with conversions:
 203         final int OUTARG_BASE = 0;  // target MH is Name.function, name Name.arguments[0]
 204         Object[] outArgs = new Object[OUTARG_BASE + INARG_COUNT];
 205 
 206         int nameCursor = INARG_LIMIT;
 207         for (int i = 0; i < INARG_COUNT; i++) {
 208             Class<?> src = srcType.parameterType(i);
 209             Class<?> dst = dstType.parameterType(i);
 210 
 211             if (!needConv[i]) {
 212                 // do nothing: difference is trivial
 213                 outArgs[OUTARG_BASE + i] = names[INARG_BASE + i];
 214                 continue;
 215             }
 216 
 217             // Tricky case analysis follows.
 218             MethodHandle fn = null;
 219             if (src.isPrimitive()) {
 220                 if (dst.isPrimitive()) {
 221                     fn = ValueConversions.convertPrimitive(src, dst);
 222                 } else {
 223                     Wrapper w = Wrapper.forPrimitiveType(src);
 224                     MethodHandle boxMethod = ValueConversions.box(w);
 225                     if (dst == w.wrapperType())
 226                         fn = boxMethod;
 227                     else
 228                         fn = boxMethod.asType(MethodType.methodType(dst, src));
 229                 }
 230             } else {
 231                 if (dst.isPrimitive()) {
 232                     // Caller has boxed a primitive.  Unbox it for the target.
 233                     Wrapper w = Wrapper.forPrimitiveType(dst);
 234                     if (level == 0 || VerifyType.isNullConversion(src, w.wrapperType())) {
 235                         fn = ValueConversions.unbox(dst);
 236                     } else if (src == Object.class || !Wrapper.isWrapperType(src)) {
 237                         // Examples:  Object->int, Number->int, Comparable->int; Byte->int, Character->int
 238                         // must include additional conversions
 239                         // src must be examined at runtime, to detect Byte, Character, etc.
 240                         MethodHandle unboxMethod = (level == 1
 241                                                     ? ValueConversions.unbox(dst)
 242                                                     : ValueConversions.unboxCast(dst));
 243                         fn = unboxMethod;
 244                     } else {
 245                         // Example: Byte->int
 246                         // Do this by reformulating the problem to Byte->byte.
 247                         Class<?> srcPrim = Wrapper.forWrapperType(src).primitiveType();
 248                         MethodHandle unbox = ValueConversions.unbox(srcPrim);
 249                         // Compose the two conversions.  FIXME:  should make two Names for this job
 250                         fn = unbox.asType(MethodType.methodType(dst, src));
 251                     }
 252                 } else {
 253                     // Simple reference conversion.
 254                     // Note:  Do not check for a class hierarchy relation
 255                     // between src and dst.  In all cases a 'null' argument
 256                     // will pass the cast conversion.
 257                     fn = ValueConversions.cast(dst);
 258                 }
 259             }
 260             Name conv = new Name(fn, names[INARG_BASE + i]);
 261             assert(names[nameCursor] == null);
 262             names[nameCursor++] = conv;
 263             assert(outArgs[OUTARG_BASE + i] == null);
 264             outArgs[OUTARG_BASE + i] = conv;
 265         }
 266 
 267         // Build argument array for the call.
 268         assert(nameCursor == OUT_CALL);
 269         names[OUT_CALL] = new Name(target, outArgs);
 270 
 271         if (RETURN_CONV < 0) {
 272             assert(OUT_CALL == names.length-1);
 273         } else {
 274             Class<?> needReturn = srcType.returnType();
 275             Class<?> haveReturn = dstType.returnType();
 276             MethodHandle fn;
 277             Object[] arg = { names[OUT_CALL] };
 278             if (haveReturn == void.class) {
 279                 // synthesize a zero value for the given void
 280                 Object zero = Wrapper.forBasicType(needReturn).zero();
 281                 fn = MethodHandles.constant(needReturn, zero);
 282                 arg = new Object[0];  // don't pass names[OUT_CALL] to conversion
 283             } else {
 284                 MethodHandle identity = MethodHandles.identity(needReturn);
 285                 MethodType needConversion = identity.type().changeParameterType(0, haveReturn);
 286                 fn = makePairwiseConvert(identity, needConversion, level);
 287             }
 288             assert(names[RETURN_CONV] == null);
 289             names[RETURN_CONV] = new Name(fn, arg);
 290             assert(RETURN_CONV == names.length-1);
 291         }
 292 
 293         LambdaForm form = new LambdaForm("convert", lambdaType.parameterCount(), names);
 294         return SimpleMethodHandle.make(srcType, form);
 295     }
 296 
 297     static MethodHandle makeReferenceIdentity(Class<?> refType) {
 298         MethodType lambdaType = MethodType.genericMethodType(1).invokerType();
 299         Name[] names = arguments(1, lambdaType);
 300         names[names.length - 1] = new Name(ValueConversions.identity(), names[1]);
 301         LambdaForm form = new LambdaForm("identity", lambdaType.parameterCount(), names);
 302         return SimpleMethodHandle.make(MethodType.methodType(refType, refType), form);
 303     }
 304 
 305     static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) {
 306         MethodType type = target.type();
 307         int last = type.parameterCount() - 1;
 308         if (type.parameterType(last) != arrayType)
 309             target = target.asType(type.changeParameterType(last, arrayType));
 310         target = target.asFixedArity();  // make sure this attribute is turned off
 311         return new AsVarargsCollector(target, target.type(), arrayType);
 312     }
 313 
 314     static class AsVarargsCollector extends MethodHandle {
 315         private final MethodHandle target;
 316         private final Class<?> arrayType;
 317         private MethodHandle cache;
 318 
 319         AsVarargsCollector(MethodHandle target, MethodType type, Class<?> arrayType) {
 320             super(type, reinvokerForm(type));
 321             this.target = target;
 322             this.arrayType = arrayType;
 323             this.cache = target.asCollector(arrayType, 0);
 324         }
 325 
 326         @Override MethodHandle reinvokerTarget() { return target; }
 327 
 328         @Override
 329         public boolean isVarargsCollector() {
 330             return true;
 331         }
 332 
 333         @Override
 334         public MethodHandle asFixedArity() {
 335             return target;
 336         }
 337 
 338         @Override
 339         public MethodHandle asType(MethodType newType) {
 340             MethodType type = this.type();
 341             int collectArg = type.parameterCount() - 1;
 342             int newArity = newType.parameterCount();
 343             if (newArity == collectArg+1 &&
 344                 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
 345                 // if arity and trailing parameter are compatible, do normal thing
 346                 return asFixedArity().asType(newType);
 347             }
 348             // check cache
 349             if (cache.type().parameterCount() == newArity)
 350                 return cache.asType(newType);
 351             // build and cache a collector
 352             int arrayLength = newArity - collectArg;
 353             MethodHandle collector;
 354             try {
 355                 collector = asFixedArity().asCollector(arrayType, arrayLength);
 356                 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector;
 357             } catch (IllegalArgumentException ex) {
 358                 throw new WrongMethodTypeException("cannot build collector", ex);
 359             }
 360             cache = collector;
 361             return collector.asType(newType);
 362         }
 363 
 364         @Override
 365         MethodHandle setVarargs(MemberName member) {
 366             if (member.isVarargs())  return this;
 367             return asFixedArity();
 368         }
 369 
 370         @Override
 371         MethodHandle viewAsType(MethodType newType) {
 372             if (newType.lastParameterType() != type().lastParameterType())
 373                 throw new InternalError();
 374             MethodHandle newTarget = asFixedArity().viewAsType(newType);
 375             // put back the varargs bit:
 376             return new AsVarargsCollector(newTarget, newType, arrayType);
 377         }
 378 
 379         @Override
 380         MemberName internalMemberName() {
 381             return asFixedArity().internalMemberName();
 382         }
 383 
 384         /*non-public*/
 385         @Override
 386         boolean isInvokeSpecial() {
 387             return asFixedArity().isInvokeSpecial();
 388         }
 389 
 390 
 391         @Override
 392         MethodHandle bindArgument(int pos, char basicType, Object value) {
 393             return asFixedArity().bindArgument(pos, basicType, value);
 394         }
 395 
 396         @Override
 397         MethodHandle bindReceiver(Object receiver) {
 398             return asFixedArity().bindReceiver(receiver);
 399         }
 400 
 401         @Override
 402         MethodHandle dropArguments(MethodType srcType, int pos, int drops) {
 403             return asFixedArity().dropArguments(srcType, pos, drops);
 404         }
 405 
 406         @Override
 407         MethodHandle permuteArguments(MethodType newType, int[] reorder) {
 408             return asFixedArity().permuteArguments(newType, reorder);
 409         }
 410     }
 411 
 412     /** Factory method:  Spread selected argument. */
 413     static MethodHandle makeSpreadArguments(MethodHandle target,
 414                                             Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
 415         MethodType targetType = target.type();
 416 
 417         for (int i = 0; i < spreadArgCount; i++) {
 418             Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i);
 419             if (arg == null)  arg = Object.class;
 420             targetType = targetType.changeParameterType(spreadArgPos + i, arg);
 421         }
 422         target = target.asType(targetType);
 423 
 424         MethodType srcType = targetType
 425                 .replaceParameterTypes(spreadArgPos, spreadArgPos + spreadArgCount, spreadArgType);
 426         // Now build a LambdaForm.
 427         MethodType lambdaType = srcType.invokerType();
 428         Name[] names = arguments(spreadArgCount + 2, lambdaType);
 429         int nameCursor = lambdaType.parameterCount();
 430         int[] indexes = new int[targetType.parameterCount()];
 431 
 432         for (int i = 0, argIndex = 1; i < targetType.parameterCount() + 1; i++, argIndex++) {
 433             Class<?> src = lambdaType.parameterType(i);
 434             if (i == spreadArgPos) {
 435                 // Spread the array.
 436                 MethodHandle aload = MethodHandles.arrayElementGetter(spreadArgType);
 437                 Name array = names[argIndex];
 438                 names[nameCursor++] = new Name(NF.checkSpreadArgument, array, spreadArgCount);
 439                 for (int j = 0; j < spreadArgCount; i++, j++) {
 440                     indexes[i] = nameCursor;
 441                     names[nameCursor++] = new Name(aload, array, j);
 442                 }
 443             } else if (i < indexes.length) {
 444                 indexes[i] = argIndex;
 445             }
 446         }
 447         assert(nameCursor == names.length-1);  // leave room for the final call
 448 
 449         // Build argument array for the call.
 450         Name[] targetArgs = new Name[targetType.parameterCount()];
 451         for (int i = 0; i < targetType.parameterCount(); i++) {
 452             int idx = indexes[i];
 453             targetArgs[i] = names[idx];
 454         }
 455         names[names.length - 1] = new Name(target, (Object[]) targetArgs);
 456 
 457         LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names);
 458         return SimpleMethodHandle.make(srcType, form);
 459     }
 460 
 461     static void checkSpreadArgument(Object av, int n) {
 462         // FIXME: regression test for bug 7141637 erroneously expects an NPE, and other tests may expect IAE
 463         // but the actual exception raised by an arity mismatch should be WMTE
 464         final boolean RAISE_RANDOM_EXCEPTIONS = true;  // FIXME: delete in JSR 292 M1
 465         if (av == null) {
 466             if (n == 0)  return;
 467             int len;
 468             if (RAISE_RANDOM_EXCEPTIONS)
 469                 len = ((Object[])av).length;  // throw NPE; but delete this after tests are fixed
 470         } else if (av instanceof Object[]) {
 471             int len = ((Object[])av).length;
 472             if (len == n)  return;
 473         } else {
 474             int len = java.lang.reflect.Array.getLength(av);
 475             if (len == n)  return;
 476         }
 477         // fall through to error:
 478         if (RAISE_RANDOM_EXCEPTIONS)
 479             throw newIllegalArgumentException("Array is not of length "+n);
 480         throw new WrongMethodTypeException("Array is not of length "+n);
 481     }
 482 
 483     /**
 484      * Pre-initialized NamedFunctions for bootstrapping purposes.
 485      * Factored in an inner class to delay initialization until first usage.
 486      */
 487     private static class NF {
 488         static final NamedFunction checkSpreadArgument;
 489         static {
 490             try {
 491                 checkSpreadArgument = new NamedFunction(MethodHandleImpl.class
 492                         .getDeclaredMethod("checkSpreadArgument", Object.class, int.class));
 493                 checkSpreadArgument.resolve();
 494             } catch (ReflectiveOperationException ex) {
 495                 throw newInternalError(ex);
 496             }
 497         }
 498     }
 499 
 500     /** Factory method:  Collect or filter selected argument(s). */
 501     static MethodHandle makeCollectArguments(MethodHandle target,
 502                 MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) {
 503         MethodType targetType = target.type();          // (a..., c, [b...])=>r
 504         MethodType collectorType = collector.type();    // (b...)=>c
 505         int collectArgCount = collectorType.parameterCount();
 506         Class<?> collectValType = collectorType.returnType();
 507         int collectValCount = (collectValType == void.class ? 0 : 1);
 508         MethodType srcType = targetType                 // (a..., [b...])=>r
 509                 .dropParameterTypes(collectArgPos, collectArgPos+collectValCount);
 510         if (!retainOriginalArgs) {                      // (a..., b...)=>r
 511             srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList());
 512         }
 513         // in  arglist: [0: ...keep1 | cpos: collect...  | cpos+cacount: keep2... ]
 514         // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ]
 515         // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ]
 516 
 517         // Now build a LambdaForm.
 518         MethodType lambdaType = srcType.invokerType();
 519         Name[] names = arguments(2, lambdaType);
 520         final int collectNamePos = names.length - 2;
 521         final int targetNamePos  = names.length - 1;
 522 
 523         Name[] collectorArgs = Arrays.copyOfRange(names, 1 + collectArgPos, 1 + collectArgPos + collectArgCount);
 524         names[collectNamePos] = new Name(collector, (Object[]) collectorArgs);
 525 
 526         // Build argument array for the target.
 527         // Incoming LF args to copy are: [ (mh) headArgs collectArgs tailArgs ].
 528         // Output argument array is [ headArgs (collectVal)? (collectArgs)? tailArgs ].
 529         Name[] targetArgs = new Name[targetType.parameterCount()];
 530         int inputArgPos  = 1;  // incoming LF args to copy to target
 531         int targetArgPos = 0;  // fill pointer for targetArgs
 532         int chunk = collectArgPos;  // |headArgs|
 533         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 534         inputArgPos  += chunk;
 535         targetArgPos += chunk;
 536         if (collectValType != void.class) {
 537             targetArgs[targetArgPos++] = names[collectNamePos];
 538         }
 539         chunk = collectArgCount;
 540         if (retainOriginalArgs) {
 541             System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 542             targetArgPos += chunk;   // optionally pass on the collected chunk
 543         }
 544         inputArgPos += chunk;
 545         chunk = targetArgs.length - targetArgPos;  // all the rest
 546         System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk);
 547         assert(inputArgPos + chunk == collectNamePos);  // use of rest of input args also
 548         names[targetNamePos] = new Name(target, (Object[]) targetArgs);
 549 
 550         LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names);
 551         return SimpleMethodHandle.make(srcType, form);
 552     }
 553 
 554     static
 555     MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
 556         return testResult ? target : fallback;
 557     }
 558 
 559     static MethodHandle SELECT_ALTERNATIVE;
 560     static MethodHandle selectAlternative() {
 561         if (SELECT_ALTERNATIVE != null)  return SELECT_ALTERNATIVE;
 562         try {
 563             SELECT_ALTERNATIVE
 564             = IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "selectAlternative",
 565                     MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class));
 566         } catch (ReflectiveOperationException ex) {
 567             throw new RuntimeException(ex);
 568         }
 569         return SELECT_ALTERNATIVE;
 570     }
 571 
 572     static
 573     MethodHandle makeGuardWithTest(MethodHandle test,
 574                                    MethodHandle target,
 575                                    MethodHandle fallback) {
 576         MethodType basicType = target.type().basicType();
 577         MethodHandle invokeBasic = MethodHandles.basicInvoker(basicType);
 578         int arity = basicType.parameterCount();
 579         int extraNames = 3;
 580         MethodType lambdaType = basicType.invokerType();
 581         Name[] names = arguments(extraNames, lambdaType);
 582 
 583         Object[] testArgs   = Arrays.copyOfRange(names, 1, 1 + arity, Object[].class);
 584         Object[] targetArgs = Arrays.copyOfRange(names, 0, 1 + arity, Object[].class);
 585 
 586         // call test
 587         names[arity + 1] = new Name(test, testArgs);
 588 
 589         // call selectAlternative
 590         Object[] selectArgs = { names[arity + 1], target, fallback };
 591         names[arity + 2] = new Name(MethodHandleImpl.selectAlternative(), selectArgs);
 592         targetArgs[0] = names[arity + 2];
 593 
 594         // call target or fallback
 595         names[arity + 3] = new Name(new NamedFunction(invokeBasic), targetArgs);
 596 
 597         LambdaForm form = new LambdaForm("guard", lambdaType.parameterCount(), names);
 598         return SimpleMethodHandle.make(target.type(), form);
 599     }
 600 
 601     private static class GuardWithCatch {
 602         private final MethodHandle target;
 603         private final Class<? extends Throwable> exType;
 604         private final MethodHandle catcher;
 605         // FIXME: Build the control flow out of foldArguments.
 606         GuardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher) {
 607             this.target = target;
 608             this.exType = exType;
 609             this.catcher = catcher;
 610         }
 611         @LambdaForm.Hidden
 612         private Object invoke_V(Object... av) throws Throwable {
 613             try {
 614                 return target.invokeExact(av);
 615             } catch (Throwable t) {
 616                 if (!exType.isInstance(t))  throw t;
 617                 return catcher.invokeExact(t, av);
 618             }
 619         }
 620         @LambdaForm.Hidden
 621         private Object invoke_L0() throws Throwable {
 622             try {
 623                 return target.invokeExact();
 624             } catch (Throwable t) {
 625                 if (!exType.isInstance(t))  throw t;
 626                 return catcher.invokeExact(t);
 627             }
 628         }
 629         @LambdaForm.Hidden
 630         private Object invoke_L1(Object a0) throws Throwable {
 631             try {
 632                 return target.invokeExact(a0);
 633             } catch (Throwable t) {
 634                 if (!exType.isInstance(t))  throw t;
 635                 return catcher.invokeExact(t, a0);
 636             }
 637         }
 638         @LambdaForm.Hidden
 639         private Object invoke_L2(Object a0, Object a1) throws Throwable {
 640             try {
 641                 return target.invokeExact(a0, a1);
 642             } catch (Throwable t) {
 643                 if (!exType.isInstance(t))  throw t;
 644                 return catcher.invokeExact(t, a0, a1);
 645             }
 646         }
 647         @LambdaForm.Hidden
 648         private Object invoke_L3(Object a0, Object a1, Object a2) throws Throwable {
 649             try {
 650                 return target.invokeExact(a0, a1, a2);
 651             } catch (Throwable t) {
 652                 if (!exType.isInstance(t))  throw t;
 653                 return catcher.invokeExact(t, a0, a1, a2);
 654             }
 655         }
 656         @LambdaForm.Hidden
 657         private Object invoke_L4(Object a0, Object a1, Object a2, Object a3) throws Throwable {
 658             try {
 659                 return target.invokeExact(a0, a1, a2, a3);
 660             } catch (Throwable t) {
 661                 if (!exType.isInstance(t))  throw t;
 662                 return catcher.invokeExact(t, a0, a1, a2, a3);
 663             }
 664         }
 665         @LambdaForm.Hidden
 666         private Object invoke_L5(Object a0, Object a1, Object a2, Object a3, Object a4) throws Throwable {
 667             try {
 668                 return target.invokeExact(a0, a1, a2, a3, a4);
 669             } catch (Throwable t) {
 670                 if (!exType.isInstance(t))  throw t;
 671                 return catcher.invokeExact(t, a0, a1, a2, a3, a4);
 672             }
 673         }
 674         @LambdaForm.Hidden
 675         private Object invoke_L6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) throws Throwable {
 676             try {
 677                 return target.invokeExact(a0, a1, a2, a3, a4, a5);
 678             } catch (Throwable t) {
 679                 if (!exType.isInstance(t))  throw t;
 680                 return catcher.invokeExact(t, a0, a1, a2, a3, a4, a5);
 681             }
 682         }
 683         @LambdaForm.Hidden
 684         private Object invoke_L7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) throws Throwable {
 685             try {
 686                 return target.invokeExact(a0, a1, a2, a3, a4, a5, a6);
 687             } catch (Throwable t) {
 688                 if (!exType.isInstance(t))  throw t;
 689                 return catcher.invokeExact(t, a0, a1, a2, a3, a4, a5, a6);
 690             }
 691         }
 692         @LambdaForm.Hidden
 693         private Object invoke_L8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) throws Throwable {
 694             try {
 695                 return target.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7);
 696             } catch (Throwable t) {
 697                 if (!exType.isInstance(t))  throw t;
 698                 return catcher.invokeExact(t, a0, a1, a2, a3, a4, a5, a6, a7);
 699             }
 700         }
 701         static MethodHandle[] makeInvokes() {
 702             ArrayList<MethodHandle> invokes = new ArrayList<>();
 703             MethodHandles.Lookup lookup = IMPL_LOOKUP;
 704             for (;;) {
 705                 int nargs = invokes.size();
 706                 String name = "invoke_L"+nargs;
 707                 MethodHandle invoke = null;
 708                 try {
 709                     invoke = lookup.findVirtual(GuardWithCatch.class, name, MethodType.genericMethodType(nargs));
 710                 } catch (ReflectiveOperationException ex) {
 711                 }
 712                 if (invoke == null)  break;
 713                 invokes.add(invoke);
 714             }
 715             assert(invokes.size() == 9);  // current number of methods
 716             return invokes.toArray(new MethodHandle[0]);
 717         };
 718         static final MethodHandle[] INVOKES = makeInvokes();
 719         // For testing use this:
 720         //static final MethodHandle[] INVOKES = Arrays.copyOf(makeInvokes(), 2);
 721         static final MethodHandle VARARGS_INVOKE;
 722         static {
 723             try {
 724                 VARARGS_INVOKE = IMPL_LOOKUP.findVirtual(GuardWithCatch.class, "invoke_V", MethodType.genericMethodType(0, true));
 725             } catch (ReflectiveOperationException ex) {
 726                 throw uncaughtException(ex);
 727             }
 728         }
 729     }
 730 
 731 
 732     static
 733     MethodHandle makeGuardWithCatch(MethodHandle target,
 734                                     Class<? extends Throwable> exType,
 735                                     MethodHandle catcher) {
 736         MethodType type = target.type();
 737         MethodType ctype = catcher.type();
 738         int nargs = type.parameterCount();
 739         if (nargs < GuardWithCatch.INVOKES.length) {
 740             MethodType gtype = type.generic();
 741             MethodType gcatchType = gtype.insertParameterTypes(0, Throwable.class);
 742             // Note: convertArguments(...2) avoids interface casts present in convertArguments(...0)
 743             MethodHandle gtarget = makePairwiseConvert(target, gtype, 2);
 744             MethodHandle gcatcher = makePairwiseConvert(catcher, gcatchType, 2);
 745             GuardWithCatch gguard = new GuardWithCatch(gtarget, exType, gcatcher);
 746             if (gtarget == null || gcatcher == null)  throw new InternalError();
 747             MethodHandle ginvoker = GuardWithCatch.INVOKES[nargs].bindReceiver(gguard);
 748             return makePairwiseConvert(ginvoker, type, 2);
 749         } else {
 750             MethodHandle gtarget = makeSpreadArguments(target, Object[].class, 0, nargs);
 751             catcher = catcher.asType(ctype.changeParameterType(0, Throwable.class));
 752             MethodHandle gcatcher = makeSpreadArguments(catcher, Object[].class, 1, nargs);
 753             GuardWithCatch gguard = new GuardWithCatch(gtarget, exType, gcatcher);
 754             if (gtarget == null || gcatcher == null)  throw new InternalError();
 755             MethodHandle ginvoker = GuardWithCatch.VARARGS_INVOKE.bindReceiver(gguard);
 756             MethodHandle gcollect = makeCollectArguments(ginvoker, ValueConversions.varargsArray(nargs), 0, false);
 757             return makePairwiseConvert(gcollect, type, 2);
 758         }
 759     }
 760 
 761     static
 762     MethodHandle throwException(MethodType type) {
 763         assert(Throwable.class.isAssignableFrom(type.parameterType(0)));
 764         int arity = type.parameterCount();
 765         if (arity > 1) {
 766             return throwException(type.dropParameterTypes(1, arity)).dropArguments(type, 1, arity-1);
 767         }
 768         return makePairwiseConvert(throwException(), type, 2);
 769     }
 770 
 771     static MethodHandle THROW_EXCEPTION;
 772     static MethodHandle throwException() {
 773         MethodHandle mh = THROW_EXCEPTION;
 774         if (mh != null)  return mh;
 775         try {
 776             mh
 777             = IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "throwException",
 778                     MethodType.methodType(Empty.class, Throwable.class));
 779         } catch (ReflectiveOperationException ex) {
 780             throw new RuntimeException(ex);
 781         }
 782         THROW_EXCEPTION = mh;
 783         return mh;
 784     }
 785     static <T extends Throwable> Empty throwException(T t) throws T { throw t; }
 786 
 787     static MethodHandle FAKE_METHOD_HANDLE_INVOKE;
 788     static
 789     MethodHandle fakeMethodHandleInvoke(MemberName method) {
 790         MethodType type = method.getInvocationType();
 791         assert(type.equals(MethodType.methodType(Object.class, Object[].class)));
 792         MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE;
 793         if (mh != null)  return mh;
 794         mh = throwException(type.insertParameterTypes(0, UnsupportedOperationException.class));
 795         mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle"));
 796         FAKE_METHOD_HANDLE_INVOKE = mh;
 797         return mh;
 798     }
 799 
 800     /**
 801      * Create an alias for the method handle which, when called,
 802      * appears to be called from the same class loader and protection domain
 803      * as hostClass.
 804      * This is an expensive no-op unless the method which is called
 805      * is sensitive to its caller.  A small number of system methods
 806      * are in this category, including Class.forName and Method.invoke.
 807      */
 808     static
 809     MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 810         return BindCaller.bindCaller(mh, hostClass);
 811     }
 812 
 813     // Put the whole mess into its own nested class.
 814     // That way we can lazily load the code and set up the constants.
 815     private static class BindCaller {
 816         static
 817         MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) {
 818             // Do not use this function to inject calls into system classes.
 819             if (hostClass == null
 820                 ||    (hostClass.isArray() ||
 821                        hostClass.isPrimitive() ||
 822                        hostClass.getName().startsWith("java.") ||
 823                        hostClass.getName().startsWith("sun."))) {
 824                 throw new InternalError();  // does not happen, and should not anyway
 825             }
 826             // For simplicity, convert mh to a varargs-like method.
 827             MethodHandle vamh = prepareForInvoker(mh);
 828             // Cache the result of makeInjectedInvoker once per argument class.
 829             MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass);
 830             return restoreToType(bccInvoker.bindTo(vamh), mh.type());
 831         }
 832 
 833         private static MethodHandle makeInjectedInvoker(Class<?> hostClass) {
 834             Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null);
 835             if (hostClass.getClassLoader() != bcc.getClassLoader())
 836                 throw new InternalError(hostClass.getName()+" (CL)");
 837             try {
 838                 if (hostClass.getProtectionDomain() != bcc.getProtectionDomain())
 839                     throw new InternalError(hostClass.getName()+" (PD)");
 840             } catch (SecurityException ex) {
 841                 // Self-check was blocked by security manager.  This is OK.
 842                 // In fact the whole try body could be turned into an assertion.
 843             }
 844             try {
 845                 MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class));
 846                 init.invokeExact();  // force initialization of the class
 847             } catch (Throwable ex) {
 848                 throw uncaughtException(ex);
 849             }
 850             MethodHandle bccInvoker;
 851             try {
 852                 MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
 853                 bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT);
 854             } catch (ReflectiveOperationException ex) {
 855                 throw uncaughtException(ex);
 856             }
 857             // Test the invoker, to ensure that it really injects into the right place.
 858             try {
 859                 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass);
 860                 Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc});
 861             } catch (Throwable ex) {
 862                 throw new InternalError(ex);
 863             }
 864             return bccInvoker;
 865         }
 866         private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() {
 867             @Override protected MethodHandle computeValue(Class<?> hostClass) {
 868                 return makeInjectedInvoker(hostClass);
 869             }
 870         };
 871 
 872         // Adapt mh so that it can be called directly from an injected invoker:
 873         private static MethodHandle prepareForInvoker(MethodHandle mh) {
 874             mh = mh.asFixedArity();
 875             MethodType mt = mh.type();
 876             int arity = mt.parameterCount();
 877             MethodHandle vamh = mh.asType(mt.generic());
 878             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 879             vamh = vamh.asSpreader(Object[].class, arity);
 880             vamh.internalForm().compileToBytecode();  // eliminate LFI stack frames
 881             return vamh;
 882         }
 883 
 884         // Undo the adapter effect of prepareForInvoker:
 885         private static MethodHandle restoreToType(MethodHandle vamh, MethodType type) {
 886             return vamh.asCollector(Object[].class, type.parameterCount()).asType(type);
 887         }
 888 
 889         private static final MethodHandle MH_checkCallerClass;
 890         static {
 891             final Class<?> THIS_CLASS = BindCaller.class;
 892             assert(checkCallerClass(THIS_CLASS, THIS_CLASS));
 893             try {
 894                 MH_checkCallerClass = IMPL_LOOKUP
 895                     .findStatic(THIS_CLASS, "checkCallerClass",
 896                                 MethodType.methodType(boolean.class, Class.class, Class.class));
 897                 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS));
 898             } catch (Throwable ex) {
 899                 throw new InternalError(ex);
 900             }
 901         }
 902 
 903         @CallerSensitive
 904         private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) {
 905             // This method is called via MH_checkCallerClass and so it's
 906             // correct to ask for the immediate caller here.
 907             Class<?> actual = Reflection.getCallerClass();
 908             if (actual != expected && actual != expected2)
 909                 throw new InternalError("found "+actual.getName()+", expected "+expected.getName()
 910                                         +(expected == expected2 ? "" : ", or else "+expected2.getName()));
 911             return true;
 912         }
 913 
 914         private static final byte[] T_BYTES;
 915         static {
 916             final Object[] values = {null};
 917             AccessController.doPrivileged(new PrivilegedAction<Void>() {
 918                     public Void run() {
 919                         try {
 920                             Class<T> tClass = T.class;
 921                             String tName = tClass.getName();
 922                             String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class";
 923                             java.net.URLConnection uconn = tClass.getResource(tResource).openConnection();
 924                             int len = uconn.getContentLength();
 925                             byte[] bytes = new byte[len];
 926                             try (java.io.InputStream str = uconn.getInputStream()) {
 927                                 int nr = str.read(bytes);
 928                                 if (nr != len)  throw new java.io.IOException(tResource);
 929                             }
 930                             values[0] = bytes;
 931                         } catch (java.io.IOException ex) {
 932                             throw new InternalError(ex);
 933                         }
 934                         return null;
 935                     }
 936                 });
 937             T_BYTES = (byte[]) values[0];
 938         }
 939 
 940         // The following class is used as a template for Unsafe.defineAnonymousClass:
 941         private static class T {
 942             static void init() { }  // side effect: initializes this class
 943             static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable {
 944                 return vamh.invokeExact(args);
 945             }
 946         }
 947     }
 948 }