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