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