JavaAdapterBytecodeGenerator.java revision 1609:c9406f325a23
1/*
2 * Copyright (c) 2010, 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
26package jdk.nashorn.internal.runtime.linker;
27
28import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL;
29import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PRIVATE;
30import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC;
31import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC;
32import static jdk.internal.org.objectweb.asm.Opcodes.ACC_SUPER;
33import static jdk.internal.org.objectweb.asm.Opcodes.ACC_VARARGS;
34import static jdk.internal.org.objectweb.asm.Opcodes.ALOAD;
35import static jdk.internal.org.objectweb.asm.Opcodes.ASTORE;
36import static jdk.internal.org.objectweb.asm.Opcodes.D2F;
37import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKESTATIC;
38import static jdk.internal.org.objectweb.asm.Opcodes.I2B;
39import static jdk.internal.org.objectweb.asm.Opcodes.I2S;
40import static jdk.internal.org.objectweb.asm.Opcodes.RETURN;
41import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup;
42import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
43import static jdk.nashorn.internal.lookup.Lookup.MH;
44import static jdk.nashorn.internal.runtime.linker.AdaptationResult.Outcome.ERROR_NO_ACCESSIBLE_CONSTRUCTOR;
45
46import java.lang.invoke.CallSite;
47import java.lang.invoke.MethodHandle;
48import java.lang.invoke.MethodHandles.Lookup;
49import java.lang.invoke.MethodType;
50import java.lang.reflect.AccessibleObject;
51import java.lang.reflect.Constructor;
52import java.lang.reflect.Method;
53import java.lang.reflect.Modifier;
54import java.security.AccessControlContext;
55import java.security.AccessController;
56import java.security.PrivilegedAction;
57import java.util.Arrays;
58import java.util.Collection;
59import java.util.HashSet;
60import java.util.Iterator;
61import java.util.List;
62import java.util.Set;
63import jdk.internal.org.objectweb.asm.ClassWriter;
64import jdk.internal.org.objectweb.asm.Handle;
65import jdk.internal.org.objectweb.asm.Label;
66import jdk.internal.org.objectweb.asm.Opcodes;
67import jdk.internal.org.objectweb.asm.Type;
68import jdk.internal.org.objectweb.asm.commons.InstructionAdapter;
69import jdk.nashorn.api.scripting.ScriptUtils;
70import jdk.nashorn.internal.codegen.CompilerConstants.Call;
71import jdk.nashorn.internal.runtime.ScriptFunction;
72import jdk.nashorn.internal.runtime.ScriptObject;
73import jdk.nashorn.internal.runtime.linker.AdaptationResult.Outcome;
74import sun.reflect.CallerSensitive;
75
76/**
77 * Generates bytecode for a Java adapter class. Used by the {@link JavaAdapterFactory}.
78 * </p><p>
79 * For every protected or public constructor in the extended class, the adapter class will have either one or two
80 * public constructors (visibility of protected constructors in the extended class is promoted to public).
81 * <li>
82 * <li>For adapter classes with instance-level overrides, a constructor taking a trailing ScriptObject argument preceded
83 * by original constructor arguments is always created on the adapter class. When such a constructor is invoked, the
84 * passed ScriptObject's member functions are used to implement and/or override methods on the original class,
85 * dispatched by name. A single JavaScript function will act as the implementation for all overloaded methods of the
86 * same name. When methods on an adapter instance are invoked, the functions are invoked having the ScriptObject passed
87 * in the instance constructor as their "this". Subsequent changes to the ScriptObject (reassignment or removal of its
88 * functions) will be reflected in the adapter instance as it is live dispatching to its members on every method invocation.
89 * {@code java.lang.Object} methods {@code equals}, {@code hashCode}, and {@code toString} can also be overridden. The
90 * only restriction is that since every JavaScript object already has a {@code toString} function through the
91 * {@code Object.prototype}, the {@code toString} in the adapter is only overridden if the passed ScriptObject has a
92 * {@code toString} function as its own property, and not inherited from a prototype. All other adapter methods can be
93 * implemented or overridden through a prototype-inherited function of the ScriptObject passed to the constructor too.
94 * </li>
95 * <li>
96 * If the original types collectively have only one abstract method, or have several of them, but all share the
97 * same name, an additional constructor for instance-level override adapter is provided for every original constructor;
98 * this one takes a ScriptFunction as its last argument preceded by original constructor arguments. This constructor
99 * will use the passed function as the implementation for all abstract methods. For consistency, any concrete methods
100 * sharing the single abstract method name will also be overridden by the function. When methods on the adapter instance
101 * are invoked, the ScriptFunction is invoked with UNDEFINED or Global as its "this" depending whether the function is
102 * strict or not.
103 * </li>
104 * <li>
105 * If the adapter being generated has class-level overrides, constructors taking same arguments as the superclass
106 * constructors are created. These constructors simply delegate to the superclass constructor. They are simply used to
107 * create instances of the adapter class, with no instance-level overrides, as they don't have them. If the original
108 * class' constructor was variable arity, the adapter constructor will also be variable arity. Protected constructors
109 * are exposed as public.
110 * </li>
111 * </ul>
112 * </p><p>
113 * For adapter methods that return values, all the JavaScript-to-Java conversions supported by Nashorn will be in effect
114 * to coerce the JavaScript function return value to the expected Java return type.
115 * </p><p>
116 * Since we are adding a trailing argument to the generated constructors in the adapter class with instance-level overrides, they will never be
117 * declared as variable arity, even if the original constructor in the superclass was declared as variable arity. The
118 * reason we are passing the additional argument at the end of the argument list instead at the front is that the
119 * source-level script expression <code>new X(a, b) { ... }</code> (which is a proprietary syntax extension Nashorn uses
120 * to resemble Java anonymous classes) is actually equivalent to <code>new X(a, b, { ... })</code>.
121 * </p><p>
122 * It is possible to create two different adapter classes: those that can have class-level overrides, and those that can
123 * have instance-level overrides. When {@link JavaAdapterFactory#getAdapterClassFor(Class[], ScriptObject)} is invoked
124 * with non-null {@code classOverrides} parameter, an adapter class is created that can have class-level overrides, and
125 * the passed script object will be used as the implementations for its methods, just as in the above case of the
126 * constructor taking a script object. Note that in the case of class-level overrides, a new adapter class is created on
127 * every invocation, and the implementation object is bound to the class, not to any instance. All created instances
128 * will share these functions. If it is required to have both class-level overrides and instance-level overrides, the
129 * class-level override adapter class should be subclassed with an instance-override adapter. Since adapters delegate to
130 * super class when an overriding method handle is not specified, this will behave as expected. It is not possible to
131 * have both class-level and instance-level overrides in the same class for security reasons: adapter classes are
132 * defined with a protection domain of their creator code, and an adapter class that has both class and instance level
133 * overrides would need to have two potentially different protection domains: one for class-based behavior and one for
134 * instance-based behavior; since Java classes can only belong to a single protection domain, this could not be
135 * implemented securely.
136 */
137final class JavaAdapterBytecodeGenerator {
138    // Field names in adapters
139    private static final String GLOBAL_FIELD_NAME = "global";
140    private static final String DELEGATE_FIELD_NAME = "delegate";
141    private static final String IS_FUNCTION_FIELD_NAME = "isFunction";
142    private static final String CALL_THIS_FIELD_NAME = "callThis";
143
144    // Initializer names
145    private static final String INIT = "<init>";
146    private static final String CLASS_INIT = "<clinit>";
147
148    // Types often used in generated bytecode
149    private static final Type OBJECT_TYPE = Type.getType(Object.class);
150    private static final Type SCRIPT_OBJECT_TYPE = Type.getType(ScriptObject.class);
151    private static final Type SCRIPT_FUNCTION_TYPE = Type.getType(ScriptFunction.class);
152
153    // JavaAdapterServices methods used in generated bytecode
154    private static final Call CHECK_FUNCTION = lookupServiceMethod("checkFunction", ScriptFunction.class, Object.class, String.class);
155    private static final Call EXPORT_RETURN_VALUE = lookupServiceMethod("exportReturnValue", Object.class, Object.class);
156    private static final Call GET_CALL_THIS = lookupServiceMethod("getCallThis", Object.class, ScriptFunction.class, Object.class);
157    private static final Call GET_CLASS_OVERRIDES = lookupServiceMethod("getClassOverrides", ScriptObject.class);
158    private static final Call GET_NON_NULL_GLOBAL = lookupServiceMethod("getNonNullGlobal", ScriptObject.class);
159    private static final Call HAS_OWN_TO_STRING = lookupServiceMethod("hasOwnToString", boolean.class, ScriptObject.class);
160    private static final Call INVOKE_NO_PERMISSIONS = lookupServiceMethod("invokeNoPermissions", void.class, MethodHandle.class, Object.class);
161    private static final Call NOT_AN_OBJECT = lookupServiceMethod("notAnObject", void.class, Object.class);
162    private static final Call SET_GLOBAL = lookupServiceMethod("setGlobal", Runnable.class, ScriptObject.class);
163    private static final Call TO_CHAR_PRIMITIVE = lookupServiceMethod("toCharPrimitive", char.class, Object.class);
164    private static final Call UNSUPPORTED = lookupServiceMethod("unsupported", UnsupportedOperationException.class);
165    private static final Call WRAP_THROWABLE = lookupServiceMethod("wrapThrowable", RuntimeException.class, Throwable.class);
166
167    // Other methods invoked by the generated bytecode
168    private static final Call UNWRAP = staticCallNoLookup(ScriptUtils.class, "unwrap", Object.class, Object.class);
169    private static final Call CHAR_VALUE_OF = staticCallNoLookup(Character.class, "valueOf", Character.class, char.class);
170    private static final Call DOUBLE_VALUE_OF = staticCallNoLookup(Double.class, "valueOf", Double.class, double.class);
171    private static final Call LONG_VALUE_OF = staticCallNoLookup(Long.class, "valueOf", Long.class, long.class);
172    private static final Call RUN = interfaceCallNoLookup(Runnable.class, "run", void.class);
173
174    // ASM handle to the bootstrap method
175    private static final Handle BOOTSTRAP_HANDLE = new Handle(H_INVOKESTATIC,
176            Type.getInternalName(JavaAdapterServices.class), "bootstrap",
177            MethodType.methodType(CallSite.class, Lookup.class, String.class,
178                    MethodType.class, int.class).toMethodDescriptorString());
179
180    // ASM handle to the bootstrap method for array populator
181    private static final Handle CREATE_ARRAY_BOOTSTRAP_HANDLE = new Handle(H_INVOKESTATIC,
182            Type.getInternalName(JavaAdapterServices.class), "createArrayBootstrap",
183            MethodType.methodType(CallSite.class, Lookup.class, String.class,
184                    MethodType.class).toMethodDescriptorString());
185
186    // Field type names used in the generated bytecode
187    private static final String SCRIPT_OBJECT_TYPE_DESCRIPTOR = SCRIPT_OBJECT_TYPE.getDescriptor();
188    private static final String OBJECT_TYPE_DESCRIPTOR = OBJECT_TYPE.getDescriptor();
189    private static final String BOOLEAN_TYPE_DESCRIPTOR = Type.BOOLEAN_TYPE.getDescriptor();
190
191    // Throwable names used in the generated bytecode
192    private static final String RUNTIME_EXCEPTION_TYPE_NAME = Type.getInternalName(RuntimeException.class);
193    private static final String ERROR_TYPE_NAME = Type.getInternalName(Error.class);
194    private static final String THROWABLE_TYPE_NAME = Type.getInternalName(Throwable.class);
195
196    // Some more frequently used method descriptors
197    private static final String GET_METHOD_PROPERTY_METHOD_DESCRIPTOR = Type.getMethodDescriptor(OBJECT_TYPE, SCRIPT_OBJECT_TYPE);
198    private static final String VOID_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE);
199
200    // Package used when the adapter can't be defined in the adaptee's package (either because it's sealed, or because
201    // it's a java.* package.
202    private static final String ADAPTER_PACKAGE_PREFIX = "jdk/nashorn/javaadapters/";
203    // Class name suffix used to append to the adaptee class name, when it can be defined in the adaptee's package.
204    private static final String ADAPTER_CLASS_NAME_SUFFIX = "$$NashornJavaAdapter";
205    private static final String JAVA_PACKAGE_PREFIX = "java/";
206    private static final int MAX_GENERATED_TYPE_NAME_LENGTH = 255;
207
208    // Method name prefix for invoking super-methods
209    static final String SUPER_PREFIX = "super$";
210
211    // Method name and type for the no-privilege finalizer delegate
212    private static final String FINALIZER_DELEGATE_NAME = "$$nashornFinalizerDelegate";
213    private static final String FINALIZER_DELEGATE_METHOD_DESCRIPTOR = Type.getMethodDescriptor(Type.VOID_TYPE, OBJECT_TYPE);
214
215    /**
216     * Collection of methods we never override: Object.clone(), Object.finalize().
217     */
218    private static final Collection<MethodInfo> EXCLUDED = getExcludedMethods();
219
220    // This is the superclass for our generated adapter.
221    private final Class<?> superClass;
222    // Interfaces implemented by our generated adapter.
223    private final List<Class<?>> interfaces;
224    // Class loader used as the parent for the class loader we'll create to load the generated class. It will be a class
225    // loader that has the visibility of all original types (class to extend and interfaces to implement) and of the
226    // Nashorn classes.
227    private final ClassLoader commonLoader;
228    // Is this a generator for the version of the class that can have overrides on the class level?
229    private final boolean classOverride;
230    // Binary name of the superClass
231    private final String superClassName;
232    // Binary name of the generated class.
233    private final String generatedClassName;
234    private final Set<String> abstractMethodNames = new HashSet<>();
235    private final String samName;
236    private final Set<MethodInfo> finalMethods = new HashSet<>(EXCLUDED);
237    private final Set<MethodInfo> methodInfos = new HashSet<>();
238    private final boolean autoConvertibleFromFunction;
239    private boolean hasExplicitFinalizer = false;
240
241    private final ClassWriter cw;
242
243    /**
244     * Creates a generator for the bytecode for the adapter for the specified superclass and interfaces.
245     * @param superClass the superclass the adapter will extend.
246     * @param interfaces the interfaces the adapter will implement.
247     * @param commonLoader the class loader that can see all of superClass, interfaces, and Nashorn classes.
248     * @param classOverride true to generate the bytecode for the adapter that has class-level overrides, false to
249     * generate the bytecode for the adapter that has instance-level overrides.
250     * @throws AdaptationException if the adapter can not be generated for some reason.
251     */
252    JavaAdapterBytecodeGenerator(final Class<?> superClass, final List<Class<?>> interfaces,
253            final ClassLoader commonLoader, final boolean classOverride) throws AdaptationException {
254        assert superClass != null && !superClass.isInterface();
255        assert interfaces != null;
256
257        this.superClass = superClass;
258        this.interfaces = interfaces;
259        this.classOverride = classOverride;
260        this.commonLoader = commonLoader;
261        cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
262            @Override
263            protected String getCommonSuperClass(final String type1, final String type2) {
264                // We need to override ClassWriter.getCommonSuperClass to use this factory's commonLoader as a class
265                // loader to find the common superclass of two types when needed.
266                return JavaAdapterBytecodeGenerator.this.getCommonSuperClass(type1, type2);
267            }
268        };
269        superClassName = Type.getInternalName(superClass);
270        generatedClassName = getGeneratedClassName(superClass, interfaces);
271
272        cw.visit(Opcodes.V1_7, ACC_PUBLIC | ACC_SUPER, generatedClassName, null, superClassName, getInternalTypeNames(interfaces));
273        generateField(GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
274        generateField(DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
275
276        gatherMethods(superClass);
277        gatherMethods(interfaces);
278        if (abstractMethodNames.size() == 1) {
279            samName = abstractMethodNames.iterator().next();
280            generateField(CALL_THIS_FIELD_NAME, OBJECT_TYPE_DESCRIPTOR);
281            generateField(IS_FUNCTION_FIELD_NAME, BOOLEAN_TYPE_DESCRIPTOR);
282        } else {
283            samName = null;
284        }
285        if(classOverride) {
286            generateClassInit();
287        }
288        autoConvertibleFromFunction = generateConstructors();
289        generateMethods();
290        generateSuperMethods();
291        if (hasExplicitFinalizer) {
292            generateFinalizerMethods();
293        }
294        // }
295        cw.visitEnd();
296    }
297
298    private void generateField(final String name, final String fieldDesc) {
299        cw.visitField(ACC_PRIVATE | ACC_FINAL | (classOverride ? ACC_STATIC : 0), name, fieldDesc, null, null).visitEnd();
300    }
301
302    JavaAdapterClassLoader createAdapterClassLoader() {
303        return new JavaAdapterClassLoader(generatedClassName, cw.toByteArray());
304    }
305
306    boolean isAutoConvertibleFromFunction() {
307        return autoConvertibleFromFunction;
308    }
309
310    private static String getGeneratedClassName(final Class<?> superType, final List<Class<?>> interfaces) {
311        // The class we use to primarily name our adapter is either the superclass, or if it is Object (meaning we're
312        // just implementing interfaces or extending Object), then the first implemented interface or Object.
313        final Class<?> namingType = superType == Object.class ? (interfaces.isEmpty()? Object.class : interfaces.get(0)) : superType;
314        final Package pkg = namingType.getPackage();
315        final String namingTypeName = Type.getInternalName(namingType);
316        final StringBuilder buf = new StringBuilder();
317        if (namingTypeName.startsWith(JAVA_PACKAGE_PREFIX) || pkg == null || pkg.isSealed()) {
318            // Can't define new classes in java.* packages
319            buf.append(ADAPTER_PACKAGE_PREFIX).append(namingTypeName);
320        } else {
321            buf.append(namingTypeName).append(ADAPTER_CLASS_NAME_SUFFIX);
322        }
323        final Iterator<Class<?>> it = interfaces.iterator();
324        if(superType == Object.class && it.hasNext()) {
325            it.next(); // Skip first interface, it was used to primarily name the adapter
326        }
327        // Append interface names to the adapter name
328        while(it.hasNext()) {
329            buf.append("$$").append(it.next().getSimpleName());
330        }
331        return buf.toString().substring(0, Math.min(MAX_GENERATED_TYPE_NAME_LENGTH, buf.length()));
332    }
333
334    /**
335     * Given a list of class objects, return an array with their binary names. Used to generate the array of interface
336     * names to implement.
337     * @param classes the classes
338     * @return an array of names
339     */
340    private static String[] getInternalTypeNames(final List<Class<?>> classes) {
341        final int interfaceCount = classes.size();
342        final String[] interfaceNames = new String[interfaceCount];
343        for(int i = 0; i < interfaceCount; ++i) {
344            interfaceNames[i] = Type.getInternalName(classes.get(i));
345        }
346        return interfaceNames;
347    }
348
349    private void generateClassInit() {
350        final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_STATIC, CLASS_INIT,
351                VOID_METHOD_DESCRIPTOR, null, null));
352
353        // Assign "global = Context.getGlobal()"
354        GET_NON_NULL_GLOBAL.invoke(mv);
355        mv.putstatic(generatedClassName, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
356
357        GET_CLASS_OVERRIDES.invoke(mv);
358        if(samName != null) {
359            // If the class is a SAM, allow having ScriptFunction passed as class overrides
360            mv.dup();
361            mv.instanceOf(SCRIPT_FUNCTION_TYPE);
362            mv.dup();
363            mv.putstatic(generatedClassName, IS_FUNCTION_FIELD_NAME, BOOLEAN_TYPE_DESCRIPTOR);
364            final Label notFunction = new Label();
365            mv.ifeq(notFunction);
366            mv.dup();
367            mv.checkcast(SCRIPT_FUNCTION_TYPE);
368            emitInitCallThis(mv);
369            mv.visitLabel(notFunction);
370        }
371        mv.putstatic(generatedClassName, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
372
373        endInitMethod(mv);
374    }
375
376    /**
377     * Emit bytecode for initializing the "callThis" field.
378     */
379    private void emitInitCallThis(final InstructionAdapter mv) {
380        loadField(mv, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
381        GET_CALL_THIS.invoke(mv);
382        if(classOverride) {
383            mv.putstatic(generatedClassName, CALL_THIS_FIELD_NAME, OBJECT_TYPE_DESCRIPTOR);
384        } else {
385            // It is presumed ALOAD 0 was already executed
386            mv.putfield(generatedClassName, CALL_THIS_FIELD_NAME, OBJECT_TYPE_DESCRIPTOR);
387        }
388    }
389
390    private boolean generateConstructors() throws AdaptationException {
391        boolean gotCtor = false;
392        boolean canBeAutoConverted = false;
393        for (final Constructor<?> ctor: superClass.getDeclaredConstructors()) {
394            final int modifier = ctor.getModifiers();
395            if((modifier & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0 && !isCallerSensitive(ctor)) {
396                canBeAutoConverted = generateConstructors(ctor) | canBeAutoConverted;
397                gotCtor = true;
398            }
399        }
400        if(!gotCtor) {
401            throw new AdaptationException(ERROR_NO_ACCESSIBLE_CONSTRUCTOR, superClass.getCanonicalName());
402        }
403        return canBeAutoConverted;
404    }
405
406    private boolean generateConstructors(final Constructor<?> ctor) {
407        if(classOverride) {
408            // Generate a constructor that just delegates to ctor. This is used with class-level overrides, when we want
409            // to create instances without further per-instance overrides.
410            generateDelegatingConstructor(ctor);
411            return false;
412        }
413
414        // Generate a constructor that delegates to ctor, but takes an additional ScriptObject parameter at the
415        // beginning of its parameter list.
416        generateOverridingConstructor(ctor, false);
417
418        if (samName == null) {
419            return false;
420        }
421        // If all our abstract methods have a single name, generate an additional constructor, one that takes a
422        // ScriptFunction as its first parameter and assigns it as the implementation for all abstract methods.
423        generateOverridingConstructor(ctor, true);
424        // If the original type only has a single abstract method name, as well as a default ctor, then it can
425        // be automatically converted from JS function.
426        return ctor.getParameterTypes().length == 0;
427    }
428
429    private void generateDelegatingConstructor(final Constructor<?> ctor) {
430        final Type originalCtorType = Type.getType(ctor);
431        final Type[] argTypes = originalCtorType.getArgumentTypes();
432
433        // All constructors must be public, even if in the superclass they were protected.
434        final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC |
435                (ctor.isVarArgs() ? ACC_VARARGS : 0), INIT,
436                Type.getMethodDescriptor(originalCtorType.getReturnType(), argTypes), null, null));
437
438        mv.visitCode();
439        emitSuperConstructorCall(mv, originalCtorType.getDescriptor());
440
441        endInitMethod(mv);
442    }
443
444    /**
445     * Generates a constructor for the instance adapter class. This constructor will take the same arguments as the supertype
446     * constructor passed as the argument here, and delegate to it. However, it will take an additional argument of
447     * either ScriptObject or ScriptFunction type (based on the value of the "fromFunction" parameter), and initialize
448     * all the method handle fields of the adapter instance with functions from the script object (or the script
449     * function itself, if that's what's passed). There is one method handle field in the adapter class for every method
450     * that can be implemented or overridden; the name of every field is same as the name of the method, with a number
451     * suffix that makes it unique in case of overloaded methods. The generated constructor will invoke
452     * {@link #getHandle(ScriptFunction, MethodType, boolean)} or {@link #getHandle(Object, String, MethodType,
453     * boolean)} to obtain the method handles; these methods make sure to add the necessary conversions and arity
454     * adjustments so that the resulting method handles can be invoked from generated methods using {@code invokeExact}.
455     * The constructor that takes a script function will only initialize the methods with the same name as the single
456     * abstract method. The constructor will also store the Nashorn global that was current at the constructor
457     * invocation time in a field named "global". The generated constructor will be public, regardless of whether the
458     * supertype constructor was public or protected. The generated constructor will not be variable arity, even if the
459     * supertype constructor was.
460     * @param ctor the supertype constructor that is serving as the base for the generated constructor.
461     * @param fromFunction true if we're generating a constructor that initializes SAM types from a single
462     * ScriptFunction passed to it, false if we're generating a constructor that initializes an arbitrary type from a
463     * ScriptObject passed to it.
464     */
465    private void generateOverridingConstructor(final Constructor<?> ctor, final boolean fromFunction) {
466        final Type originalCtorType = Type.getType(ctor);
467        final Type[] originalArgTypes = originalCtorType.getArgumentTypes();
468        final int argLen = originalArgTypes.length;
469        final Type[] newArgTypes = new Type[argLen + 1];
470
471        // Insert ScriptFunction|ScriptObject as the last argument to the constructor
472        final Type extraArgumentType = fromFunction ? SCRIPT_FUNCTION_TYPE : SCRIPT_OBJECT_TYPE;
473        newArgTypes[argLen] = extraArgumentType;
474        System.arraycopy(originalArgTypes, 0, newArgTypes, 0, argLen);
475
476        // All constructors must be public, even if in the superclass they were protected.
477        // Existing super constructor <init>(this, args...) triggers generating <init>(this, args..., delegate).
478        // Any variable arity constructors become fixed-arity with explicit array arguments.
479        final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC, INIT,
480                Type.getMethodDescriptor(originalCtorType.getReturnType(), newArgTypes), null, null));
481
482        mv.visitCode();
483        // First, invoke super constructor with original arguments.
484        final int extraArgOffset = emitSuperConstructorCall(mv, originalCtorType.getDescriptor());
485
486        // Assign "this.global = Context.getGlobal()"
487        mv.visitVarInsn(ALOAD, 0);
488        GET_NON_NULL_GLOBAL.invoke(mv);
489        mv.putfield(generatedClassName, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
490
491        // Assign "this.delegate = delegate"
492        mv.visitVarInsn(ALOAD, 0);
493        mv.visitVarInsn(ALOAD, extraArgOffset);
494        mv.putfield(generatedClassName, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
495
496        if (fromFunction) {
497            // Assign "isFunction = true"
498            mv.visitVarInsn(ALOAD, 0);
499            mv.iconst(1);
500            mv.putfield(generatedClassName, IS_FUNCTION_FIELD_NAME, BOOLEAN_TYPE_DESCRIPTOR);
501
502            mv.visitVarInsn(ALOAD, 0);
503            mv.visitVarInsn(ALOAD, extraArgOffset);
504            emitInitCallThis(mv);
505        }
506
507        endInitMethod(mv);
508
509        if (! fromFunction) {
510            newArgTypes[argLen] = OBJECT_TYPE;
511            final InstructionAdapter mv2 = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC, INIT,
512                    Type.getMethodDescriptor(originalCtorType.getReturnType(), newArgTypes), null, null));
513            generateOverridingConstructorWithObjectParam(mv2, originalCtorType.getDescriptor());
514        }
515    }
516
517    // Object additional param accepting constructor - generated to handle null and undefined value
518    // for script adapters. This is effectively to throw TypeError on such script adapters. See
519    // JavaAdapterServices.getHandle as well.
520    private void generateOverridingConstructorWithObjectParam(final InstructionAdapter mv, final String ctorDescriptor) {
521        mv.visitCode();
522        final int extraArgOffset = emitSuperConstructorCall(mv, ctorDescriptor);
523        mv.visitVarInsn(ALOAD, extraArgOffset);
524        NOT_AN_OBJECT.invoke(mv);
525        endInitMethod(mv);
526    }
527
528    private static void endInitMethod(final InstructionAdapter mv) {
529        mv.visitInsn(RETURN);
530        endMethod(mv);
531    }
532
533    private static void endMethod(final InstructionAdapter mv) {
534        mv.visitMaxs(0, 0);
535        mv.visitEnd();
536    }
537
538    /**
539     * Encapsulation of the information used to generate methods in the adapter classes. Basically, a wrapper around the
540     * reflective Method object, a cached MethodType, and the name of the field in the adapter class that will hold the
541     * method handle serving as the implementation of this method in adapter instances.
542     *
543     */
544    private static class MethodInfo {
545        private final Method method;
546        private final MethodType type;
547
548        private MethodInfo(final Class<?> clazz, final String name, final Class<?>... argTypes) throws NoSuchMethodException {
549            this(clazz.getDeclaredMethod(name, argTypes));
550        }
551
552        private MethodInfo(final Method method) {
553            this.method = method;
554            this.type   = MH.type(method.getReturnType(), method.getParameterTypes());
555        }
556
557        @Override
558        public boolean equals(final Object obj) {
559            return obj instanceof MethodInfo && equals((MethodInfo)obj);
560        }
561
562        private boolean equals(final MethodInfo other) {
563            // Only method name and type are used for comparison; method handle field name is not.
564            return getName().equals(other.getName()) && type.equals(other.type);
565        }
566
567        String getName() {
568            return method.getName();
569        }
570
571        @Override
572        public int hashCode() {
573            return getName().hashCode() ^ type.hashCode();
574        }
575    }
576
577    private void generateMethods() {
578        for(final MethodInfo mi: methodInfos) {
579            generateMethod(mi);
580        }
581    }
582
583    /**
584     * Generates a method in the adapter class that adapts a method from the
585     * original class. The generated method will either invoke the delegate
586     * using a CALL dynamic operation call site (if it is a SAM method and the
587     * delegate is a ScriptFunction), or invoke GET_METHOD_PROPERTY dynamic
588     * operation with the method name as the argument and then invoke the
589     * returned ScriptFunction using the CALL dynamic operation. If
590     * GET_METHOD_PROPERTY returns null or undefined (that is, the JS object
591     * doesn't provide an implementation for the method) then the method will
592     * either do a super invocation to base class, or if the method is abstract,
593     * throw an {@link UnsupportedOperationException}. Finally, if
594     * GET_METHOD_PROPERTY returns something other than a ScriptFunction, null,
595     * or undefined, a TypeError is thrown. The current Global is checked before
596     * the dynamic operations, and if it is different  than the Global used to
597     * create the adapter, the creating Global is set to be the current Global.
598     * In this case, the previously current Global is restored after the
599     * invocation. If CALL results in a Throwable that is not one of the
600     * method's declared exceptions, and is not an unchecked throwable, then it
601     * is wrapped into a {@link RuntimeException} and the runtime exception is
602     * thrown.
603     * @param mi the method info describing the method to be generated.
604     */
605    private void generateMethod(final MethodInfo mi) {
606        final Method method = mi.method;
607        final Class<?>[] exceptions = method.getExceptionTypes();
608        final String[] exceptionNames = getExceptionNames(exceptions);
609        final MethodType type = mi.type;
610        final String methodDesc = type.toMethodDescriptorString();
611        final String name = mi.getName();
612
613        final Type asmType = Type.getMethodType(methodDesc);
614        final Type[] asmArgTypes = asmType.getArgumentTypes();
615
616        final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(getAccessModifiers(method), name,
617                methodDesc, null, exceptionNames));
618        mv.visitCode();
619
620        final Class<?> returnType = type.returnType();
621        final Type asmReturnType = Type.getType(returnType);
622
623        // Determine the first index for a local variable
624        int nextLocalVar = 1; // "this" is at 0
625        for(final Type t: asmArgTypes) {
626            nextLocalVar += t.getSize();
627        }
628        // Set our local variable index
629        final int globalRestoringRunnableVar = nextLocalVar++;
630
631        // Load the creatingGlobal object
632        loadField(mv, GLOBAL_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
633
634        // stack: [creatingGlobal]
635        SET_GLOBAL.invoke(mv);
636        // stack: [runnable]
637        mv.visitVarInsn(ASTORE, globalRestoringRunnableVar);
638        // stack: []
639
640        final Label tryBlockStart = new Label();
641        mv.visitLabel(tryBlockStart);
642
643        final Label callCallee = new Label();
644        final Label defaultBehavior = new Label();
645        // If this is a SAM type...
646        if (samName != null) {
647            // ...every method will be checking whether we're initialized with a
648            // function.
649            loadField(mv, IS_FUNCTION_FIELD_NAME, BOOLEAN_TYPE_DESCRIPTOR);
650            // stack: [isFunction]
651            if (name.equals(samName)) {
652                final Label notFunction = new Label();
653                mv.ifeq(notFunction);
654                // stack: []
655                // If it's a SAM method, it'll load delegate as the "callee" and
656                // "callThis" as "this" for the call if delegate is a function.
657                loadField(mv, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
658                // NOTE: if we added "mv.checkcast(SCRIPT_FUNCTION_TYPE);" here
659                // we could emit the invokedynamic CALL instruction with signature
660                // (ScriptFunction, Object, ...) instead of (Object, Object, ...).
661                // We could combine this with an optimization in
662                // ScriptFunction.findCallMethod where it could link a call with a
663                // thinner guard when the call site statically guarantees that the
664                // callee argument is a ScriptFunction. Additionally, we could use
665                // a "ScriptFunction function" field in generated classes instead
666                // of a "boolean isFunction" field to avoid the checkcast.
667                loadField(mv, CALL_THIS_FIELD_NAME, OBJECT_TYPE_DESCRIPTOR);
668                // stack: [callThis, delegate]
669                mv.goTo(callCallee);
670                mv.visitLabel(notFunction);
671            } else {
672                // If it's not a SAM method, and the delegate is a function,
673                // it'll fall back to default behavior
674                mv.ifne(defaultBehavior);
675                // stack: []
676            }
677        }
678
679        // At this point, this is either not a SAM method or the delegate is
680        // not a ScriptFunction. We need to emit a GET_METHOD_PROPERTY Nashorn
681        // invokedynamic.
682
683        if(name.equals("toString")) {
684            // Since every JS Object has a toString, we only override
685            // "String toString()" it if it's explicitly specified on the object.
686            loadField(mv, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
687            // stack: [delegate]
688            HAS_OWN_TO_STRING.invoke(mv);
689            // stack: [hasOwnToString]
690            mv.ifeq(defaultBehavior);
691        }
692
693        loadField(mv, DELEGATE_FIELD_NAME, SCRIPT_OBJECT_TYPE_DESCRIPTOR);
694        mv.dup();
695        // stack: [delegate, delegate]
696        final String encodedName = NameCodec.encode(name);
697        mv.visitInvokeDynamicInsn(encodedName,
698                GET_METHOD_PROPERTY_METHOD_DESCRIPTOR, BOOTSTRAP_HANDLE,
699                NashornCallSiteDescriptor.GET_METHOD_PROPERTY);
700        // stack: [callee, delegate]
701        mv.visitLdcInsn(name);
702        // stack: [name, callee, delegate]
703        CHECK_FUNCTION.invoke(mv);
704        // stack: [fnCalleeOrNull, delegate]
705        final Label hasFunction = new Label();
706        mv.dup();
707        // stack: [fnCalleeOrNull, fnCalleeOrNull, delegate]
708        mv.ifnonnull(hasFunction);
709        // stack: [null, delegate]
710        // If it's null or undefined, clear stack and fall back to default
711        // behavior.
712        mv.pop2();
713        // stack: []
714
715        // We can also arrive here from check for "delegate instanceof ScriptFunction"
716        // in a non-SAM method as well as from a check for "hasOwnToString(delegate)"
717        // for a toString delegate.
718        mv.visitLabel(defaultBehavior);
719        final Runnable emitFinally = ()->emitFinally(mv, globalRestoringRunnableVar);
720        final Label normalFinally = new Label();
721        if(Modifier.isAbstract(method.getModifiers())) {
722            // If the super method is abstract, throw UnsupportedOperationException
723            UNSUPPORTED.invoke(mv);
724            // NOTE: no need to invoke emitFinally.run() as we're inside the
725            // tryBlockStart/tryBlockEnd range, so throwing this exception will
726            // transfer control to the rethrow handler and the finally block in it
727            // will execute.
728            mv.athrow();
729        } else {
730            // If the super method is not abstract, delegate to it.
731            emitSuperCall(mv, method.getDeclaringClass(), name, methodDesc);
732            mv.goTo(normalFinally);
733        }
734
735        mv.visitLabel(hasFunction);
736        // stack: [callee, delegate]
737        mv.swap();
738        // stack [delegate, callee]
739        mv.visitLabel(callCallee);
740
741
742        // Load all parameters back on stack for dynamic invocation.
743
744        int varOffset = 1;
745        // If the param list length is more than 253 slots, we can't invoke it
746        // directly as with (callee, this) it'll exceed 255.
747        final boolean isVarArgCall = getParamListLengthInSlots(asmArgTypes) > 253;
748        for (final Type t : asmArgTypes) {
749            mv.load(varOffset, t);
750            convertParam(mv, t, isVarArgCall);
751            varOffset += t.getSize();
752        }
753        // stack: [args..., callee, delegate]
754
755        // If the resulting parameter list length is too long...
756        if (isVarArgCall) {
757            // ... we pack the parameters (except callee and this) into an array
758            // and use Nashorn vararg invocation.
759            mv.visitInvokeDynamicInsn(NameCodec.EMPTY_NAME,
760                    getArrayCreatorMethodType(type).toMethodDescriptorString(),
761                    CREATE_ARRAY_BOOTSTRAP_HANDLE);
762        }
763
764        // Invoke the target method handle
765        mv.visitInvokeDynamicInsn(encodedName,
766                getCallMethodType(isVarArgCall, type).toMethodDescriptorString(),
767                BOOTSTRAP_HANDLE, NashornCallSiteDescriptor.CALL);
768        // stack: [returnValue]
769        convertReturnValue(mv, returnType);
770        mv.visitLabel(normalFinally);
771        emitFinally.run();
772        mv.areturn(asmReturnType);
773
774        // If Throwable is not declared, we need an adapter from Throwable to RuntimeException
775        final boolean throwableDeclared = isThrowableDeclared(exceptions);
776        final Label throwableHandler;
777        if (!throwableDeclared) {
778            // Add "throw new RuntimeException(Throwable)" handler for Throwable
779            throwableHandler = new Label();
780            mv.visitLabel(throwableHandler);
781            WRAP_THROWABLE.invoke(mv);
782            // Fall through to rethrow handler
783        } else {
784            throwableHandler = null;
785        }
786        final Label rethrowHandler = new Label();
787        mv.visitLabel(rethrowHandler);
788        // Rethrow handler for RuntimeException, Error, and all declared exception types
789        emitFinally.run();
790        mv.athrow();
791
792        if(throwableDeclared) {
793            mv.visitTryCatchBlock(tryBlockStart, normalFinally, rethrowHandler, THROWABLE_TYPE_NAME);
794            assert throwableHandler == null;
795        } else {
796            mv.visitTryCatchBlock(tryBlockStart, normalFinally, rethrowHandler, RUNTIME_EXCEPTION_TYPE_NAME);
797            mv.visitTryCatchBlock(tryBlockStart, normalFinally, rethrowHandler, ERROR_TYPE_NAME);
798            for(final String excName: exceptionNames) {
799                mv.visitTryCatchBlock(tryBlockStart, normalFinally, rethrowHandler, excName);
800            }
801            mv.visitTryCatchBlock(tryBlockStart, normalFinally, throwableHandler, THROWABLE_TYPE_NAME);
802        }
803        endMethod(mv);
804    }
805
806    private static MethodType getCallMethodType(final boolean isVarArgCall, final MethodType type) {
807        final Class<?>[] callParamTypes;
808        if (isVarArgCall) {
809            // Variable arity calls are always (Object callee, Object this, Object[] params)
810            callParamTypes = new Class<?>[] { Object.class, Object.class, Object[].class };
811        } else {
812            // Adjust invocation type signature for conversions we instituted in
813            // convertParam; also, byte and short get passed as ints.
814            final Class<?>[] origParamTypes = type.parameterArray();
815            callParamTypes = new Class<?>[origParamTypes.length + 2];
816            callParamTypes[0] = Object.class; // callee; could be ScriptFunction.class ostensibly
817            callParamTypes[1] = Object.class; // this
818            for(int i = 0; i < origParamTypes.length; ++i) {
819                callParamTypes[i + 2] = getNashornParamType(origParamTypes[i], false);
820            }
821        }
822        return MethodType.methodType(getNashornReturnType(type.returnType()), callParamTypes);
823    }
824
825    private static MethodType getArrayCreatorMethodType(final MethodType type) {
826        final Class<?>[] callParamTypes = type.parameterArray();
827        for(int i = 0; i < callParamTypes.length; ++i) {
828            callParamTypes[i] = getNashornParamType(callParamTypes[i], true);
829        }
830        return MethodType.methodType(Object[].class, callParamTypes);
831    }
832
833    private static Class<?> getNashornParamType(final Class<?> clazz, final boolean varArg) {
834        if (clazz == byte.class || clazz == short.class) {
835            return int.class;
836        } else if (clazz == float.class) {
837            // If using variable arity, we'll pass a Double instead of double
838            // so that floats don't extend the length of the parameter list.
839            // We return Object.class instead of Double.class though as the
840            // array collector will anyway operate on Object.
841            return varArg ? Object.class : double.class;
842        } else if (!clazz.isPrimitive() || clazz == long.class || clazz == char.class) {
843            return Object.class;
844        }
845        return clazz;
846    }
847
848    private static Class<?> getNashornReturnType(final Class<?> clazz) {
849        if (clazz == byte.class || clazz == short.class) {
850            return int.class;
851        } else if (clazz == float.class) {
852            return double.class;
853        } else if (clazz == void.class || clazz == char.class) {
854            return Object.class;
855        }
856        return clazz;
857    }
858
859
860    private void loadField(final InstructionAdapter mv, final String name, final String desc) {
861        if(classOverride) {
862            mv.getstatic(generatedClassName, name, desc);
863        } else {
864            mv.visitVarInsn(ALOAD, 0);
865            mv.getfield(generatedClassName, name, desc);
866        }
867    }
868
869    private static void convertReturnValue(final InstructionAdapter mv, final Class<?> origReturnType) {
870        if (origReturnType == void.class) {
871            mv.pop();
872        } else if (origReturnType == Object.class) {
873            // Must hide ConsString (and potentially other internal Nashorn types) from callers
874            EXPORT_RETURN_VALUE.invoke(mv);
875        } else if (origReturnType == byte.class) {
876            mv.visitInsn(I2B);
877        } else if (origReturnType == short.class) {
878            mv.visitInsn(I2S);
879        } else if (origReturnType == float.class) {
880            mv.visitInsn(D2F);
881        } else if (origReturnType == char.class) {
882            TO_CHAR_PRIMITIVE.invoke(mv);
883        }
884    }
885
886    /**
887     * Emits instruction for converting a parameter on the top of the stack to
888     * a type that is understood by Nashorn.
889     * @param mv the current method visitor
890     * @param t the type on the top of the stack
891     * @param varArg if the invocation will be variable arity
892     */
893    private static void convertParam(final InstructionAdapter mv, final Type t, final boolean varArg) {
894        // We perform conversions of some primitives to accommodate types that
895        // Nashorn can handle.
896        switch(t.getSort()) {
897        case Type.CHAR:
898            // Chars are boxed, as we don't know if the JS code wants to treat
899            // them as an effective "unsigned short" or as a single-char string.
900            CHAR_VALUE_OF.invoke(mv);
901            break;
902        case Type.FLOAT:
903            // Floats are widened to double.
904            mv.visitInsn(Opcodes.F2D);
905            if (varArg) {
906                // We'll be boxing everything anyway for the vararg invocation,
907                // so we might as well do it proactively here and thus not cause
908                // a widening in the number of slots, as that could even make
909                // the array creation invocation go over 255 param slots.
910                DOUBLE_VALUE_OF.invoke(mv);
911            }
912            break;
913        case Type.LONG:
914            // Longs are boxed as Nashorn can't represent them precisely as a
915            // primitive number.
916            LONG_VALUE_OF.invoke(mv);
917            break;
918        case Type.OBJECT:
919            if(t.equals(OBJECT_TYPE)) {
920                // Object can carry a ScriptObjectMirror and needs to be unwrapped
921                // before passing into a Nashorn function.
922                UNWRAP.invoke(mv);
923            }
924            break;
925        }
926    }
927
928    private static int getParamListLengthInSlots(final Type[] paramTypes) {
929        int len = paramTypes.length;
930        for(final Type t: paramTypes) {
931            final int sort = t.getSort();
932            if (sort == Type.FLOAT || sort == Type.DOUBLE) {
933                // Floats are widened to double, so they'll take up two slots.
934                // Longs on the other hand are always boxed, so their width
935                // becomes 1 and thus they don't contribute an extra slot here.
936                ++len;
937            }
938        }
939        return len;
940    }
941    /**
942     * Emit code to restore the previous Nashorn Context when needed.
943     * @param mv the instruction adapter
944     * @param globalRestoringRunnableVar index of the local variable holding the reference to the global restoring Runnable
945     */
946    private static void emitFinally(final InstructionAdapter mv, final int globalRestoringRunnableVar) {
947        mv.visitVarInsn(ALOAD, globalRestoringRunnableVar);
948        RUN.invoke(mv);
949    }
950
951    private static boolean isThrowableDeclared(final Class<?>[] exceptions) {
952        for (final Class<?> exception : exceptions) {
953            if (exception == Throwable.class) {
954                return true;
955            }
956        }
957        return false;
958    }
959
960    private void generateSuperMethods() {
961        for(final MethodInfo mi: methodInfos) {
962            if(!Modifier.isAbstract(mi.method.getModifiers())) {
963                generateSuperMethod(mi);
964            }
965        }
966    }
967
968    private void generateSuperMethod(final MethodInfo mi) {
969        final Method method = mi.method;
970
971        final String methodDesc = mi.type.toMethodDescriptorString();
972        final String name = mi.getName();
973
974        final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(getAccessModifiers(method),
975                SUPER_PREFIX + name, methodDesc, null, getExceptionNames(method.getExceptionTypes())));
976        mv.visitCode();
977
978        emitSuperCall(mv, method.getDeclaringClass(), name, methodDesc);
979        mv.areturn(Type.getType(mi.type.returnType()));
980        endMethod(mv);
981    }
982
983    // find the appropriate super type to use for invokespecial on the given interface
984    private Class<?> findInvokespecialOwnerFor(final Class<?> cl) {
985        assert Modifier.isInterface(cl.getModifiers()) : cl + " is not an interface";
986
987        if (cl.isAssignableFrom(superClass)) {
988            return superClass;
989        }
990
991        for (final Class<?> iface : interfaces) {
992             if (cl.isAssignableFrom(iface)) {
993                 return iface;
994             }
995        }
996
997        // we better that interface that extends the given interface!
998        throw new AssertionError("can't find the class/interface that extends " + cl);
999    }
1000
1001    private int emitSuperConstructorCall(final InstructionAdapter mv, final String methodDesc) {
1002        return emitSuperCall(mv, null, INIT, methodDesc, true);
1003    }
1004
1005    private int emitSuperCall(final InstructionAdapter mv, final Class<?> owner, final String name, final String methodDesc) {
1006        return emitSuperCall(mv, owner, name, methodDesc, false);
1007    }
1008
1009    private int emitSuperCall(final InstructionAdapter mv, final Class<?> owner, final String name, final String methodDesc, final boolean constructor) {
1010        mv.visitVarInsn(ALOAD, 0);
1011        int nextParam = 1;
1012        final Type methodType = Type.getMethodType(methodDesc);
1013        for(final Type t: methodType.getArgumentTypes()) {
1014            mv.load(nextParam, t);
1015            nextParam += t.getSize();
1016        }
1017
1018        // default method - non-abstract, interface method
1019        if (!constructor && Modifier.isInterface(owner.getModifiers())) {
1020            // we should call default method on the immediate "super" type - not on (possibly)
1021            // the indirectly inherited interface class!
1022            mv.invokespecial(Type.getInternalName(findInvokespecialOwnerFor(owner)), name, methodDesc, false);
1023        } else {
1024            mv.invokespecial(superClassName, name, methodDesc, false);
1025        }
1026        return nextParam;
1027    }
1028
1029    private void generateFinalizerMethods() {
1030        generateFinalizerDelegate();
1031        generateFinalizerOverride();
1032    }
1033
1034    private void generateFinalizerDelegate() {
1035        // Generate a delegate that will be invoked from the no-permission trampoline. Note it can be private, as we'll
1036        // refer to it with a MethodHandle constant pool entry in the overridden finalize() method (see
1037        // generateFinalizerOverride()).
1038        final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_PRIVATE | ACC_STATIC,
1039                FINALIZER_DELEGATE_NAME, FINALIZER_DELEGATE_METHOD_DESCRIPTOR, null, null));
1040
1041        // Simply invoke super.finalize()
1042        mv.visitVarInsn(ALOAD, 0);
1043        mv.checkcast(Type.getType(generatedClassName));
1044        mv.invokespecial(superClassName, "finalize", VOID_METHOD_DESCRIPTOR, false);
1045
1046        mv.visitInsn(RETURN);
1047        endMethod(mv);
1048    }
1049
1050    private void generateFinalizerOverride() {
1051        final InstructionAdapter mv = new InstructionAdapter(cw.visitMethod(ACC_PUBLIC, "finalize",
1052                VOID_METHOD_DESCRIPTOR, null, null));
1053        // Overridden finalizer will take a MethodHandle to the finalizer delegating method, ...
1054        mv.aconst(new Handle(Opcodes.H_INVOKESTATIC, generatedClassName, FINALIZER_DELEGATE_NAME,
1055                FINALIZER_DELEGATE_METHOD_DESCRIPTOR));
1056        mv.visitVarInsn(ALOAD, 0);
1057        // ...and invoke it through JavaAdapterServices.invokeNoPermissions
1058        INVOKE_NO_PERMISSIONS.invoke(mv);
1059        mv.visitInsn(RETURN);
1060        endMethod(mv);
1061    }
1062
1063    private static String[] getExceptionNames(final Class<?>[] exceptions) {
1064        final String[] exceptionNames = new String[exceptions.length];
1065        for (int i = 0; i < exceptions.length; ++i) {
1066            exceptionNames[i] = Type.getInternalName(exceptions[i]);
1067        }
1068        return exceptionNames;
1069    }
1070
1071    private static int getAccessModifiers(final Method method) {
1072        return ACC_PUBLIC | (method.isVarArgs() ? ACC_VARARGS : 0);
1073    }
1074
1075    /**
1076     * Gathers methods that can be implemented or overridden from the specified type into this factory's
1077     * {@link #methodInfos} set. It will add all non-final, non-static methods that are either public or protected from
1078     * the type if the type itself is public. If the type is a class, the method will recursively invoke itself for its
1079     * superclass and the interfaces it implements, and add further methods that were not directly declared on the
1080     * class.
1081     * @param type the type defining the methods.
1082     */
1083    private void gatherMethods(final Class<?> type) throws AdaptationException {
1084        if (Modifier.isPublic(type.getModifiers())) {
1085            final Method[] typeMethods = type.isInterface() ? type.getMethods() : type.getDeclaredMethods();
1086
1087            for (final Method typeMethod: typeMethods) {
1088                final String name = typeMethod.getName();
1089                if(name.startsWith(SUPER_PREFIX)) {
1090                    continue;
1091                }
1092                final int m = typeMethod.getModifiers();
1093                if (Modifier.isStatic(m)) {
1094                    continue;
1095                }
1096                if (Modifier.isPublic(m) || Modifier.isProtected(m)) {
1097                    // Is it a "finalize()"?
1098                    if(name.equals("finalize") && typeMethod.getParameterCount() == 0) {
1099                        if(type != Object.class) {
1100                            hasExplicitFinalizer = true;
1101                            if(Modifier.isFinal(m)) {
1102                                // Must be able to override an explicit finalizer
1103                                throw new AdaptationException(Outcome.ERROR_FINAL_FINALIZER, type.getCanonicalName());
1104                            }
1105                        }
1106                        continue;
1107                    }
1108
1109                    final MethodInfo mi = new MethodInfo(typeMethod);
1110                    if (Modifier.isFinal(m) || isCallerSensitive(typeMethod)) {
1111                        finalMethods.add(mi);
1112                    } else if (!finalMethods.contains(mi) && methodInfos.add(mi) && Modifier.isAbstract(m)) {
1113                        abstractMethodNames.add(mi.getName());
1114                    }
1115                }
1116            }
1117        }
1118        // If the type is a class, visit its superclasses and declared interfaces. If it's an interface, we're done.
1119        // Needing to invoke the method recursively for a non-interface Class object is the consequence of needing to
1120        // see all declared protected methods, and Class.getDeclaredMethods() doesn't provide those declared in a
1121        // superclass. For interfaces, we used Class.getMethods(), as we're only interested in public ones there, and
1122        // getMethods() does provide those declared in a superinterface.
1123        if (!type.isInterface()) {
1124            final Class<?> superType = type.getSuperclass();
1125            if (superType != null) {
1126                gatherMethods(superType);
1127            }
1128            for (final Class<?> itf: type.getInterfaces()) {
1129                gatherMethods(itf);
1130            }
1131        }
1132    }
1133
1134    private void gatherMethods(final List<Class<?>> classes) throws AdaptationException {
1135        for(final Class<?> c: classes) {
1136            gatherMethods(c);
1137        }
1138    }
1139
1140    private static final AccessControlContext GET_DECLARED_MEMBERS_ACC_CTXT = ClassAndLoader.createPermAccCtxt("accessDeclaredMembers");
1141
1142    /**
1143     * Creates a collection of methods that are not final, but we still never allow them to be overridden in adapters,
1144     * as explicitly declaring them automatically is a bad idea. Currently, this means {@code Object.finalize()} and
1145     * {@code Object.clone()}.
1146     * @return a collection of method infos representing those methods that we never override in adapter classes.
1147     */
1148    private static Collection<MethodInfo> getExcludedMethods() {
1149        return AccessController.doPrivileged(new PrivilegedAction<Collection<MethodInfo>>() {
1150            @Override
1151            public Collection<MethodInfo> run() {
1152                try {
1153                    return Arrays.asList(
1154                            new MethodInfo(Object.class, "finalize"),
1155                            new MethodInfo(Object.class, "clone"));
1156                } catch (final NoSuchMethodException e) {
1157                    throw new AssertionError(e);
1158                }
1159            }
1160        }, GET_DECLARED_MEMBERS_ACC_CTXT);
1161    }
1162
1163    private String getCommonSuperClass(final String type1, final String type2) {
1164        try {
1165            final Class<?> c1 = Class.forName(type1.replace('/', '.'), false, commonLoader);
1166            final Class<?> c2 = Class.forName(type2.replace('/', '.'), false, commonLoader);
1167            if (c1.isAssignableFrom(c2)) {
1168                return type1;
1169            }
1170            if (c2.isAssignableFrom(c1)) {
1171                return type2;
1172            }
1173            if (c1.isInterface() || c2.isInterface()) {
1174                return OBJECT_TYPE.getInternalName();
1175            }
1176            return assignableSuperClass(c1, c2).getName().replace('.', '/');
1177        } catch(final ClassNotFoundException e) {
1178            throw new RuntimeException(e);
1179        }
1180    }
1181
1182    private static Class<?> assignableSuperClass(final Class<?> c1, final Class<?> c2) {
1183        final Class<?> superClass = c1.getSuperclass();
1184        return superClass.isAssignableFrom(c2) ? superClass : assignableSuperClass(superClass, c2);
1185    }
1186
1187    private static boolean isCallerSensitive(final AccessibleObject e) {
1188        return e.isAnnotationPresent(CallerSensitive.class);
1189    }
1190
1191    private static final Call lookupServiceMethod(final String name, final Class<?> rtype, final Class<?>... ptypes) {
1192        return staticCallNoLookup(JavaAdapterServices.class, name, rtype, ptypes);
1193    }
1194}
1195