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.nashorn.internal.lookup.Lookup.MH;
  29 
  30 import java.lang.invoke.MethodHandle;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.invoke.MethodHandles.Lookup;
  33 import java.lang.invoke.MethodType;
  34 import java.lang.reflect.Modifier;
  35 import java.security.AccessControlContext;
  36 import java.security.AccessController;
  37 import java.security.CodeSigner;
  38 import java.security.CodeSource;
  39 import java.security.Permissions;
  40 import java.security.PrivilegedAction;
  41 import java.security.ProtectionDomain;
  42 import java.util.ArrayList;
  43 import java.util.Arrays;
  44 import java.util.Collections;
  45 import java.util.HashMap;
  46 import java.util.List;
  47 import java.util.Map;
  48 import java.util.concurrent.ConcurrentHashMap;
  49 import jdk.internal.dynalink.beans.StaticClass;
  50 import jdk.internal.dynalink.support.LinkRequestImpl;
  51 import jdk.nashorn.internal.objects.NativeJava;
  52 import jdk.nashorn.internal.runtime.Context;
  53 import jdk.nashorn.internal.runtime.ECMAException;
  54 import jdk.nashorn.internal.runtime.ScriptFunction;
  55 import jdk.nashorn.internal.runtime.ScriptObject;
  56 
  57 /**
  58  * <p>A factory class that generates adapter classes. Adapter classes allow implementation of Java interfaces and
  59  * extending of Java classes from JavaScript. For every combination of a superclass to extend and interfaces to
  60  * implement (collectively: "original types"), exactly one adapter class is generated that extends the specified
  61  * superclass and implements the specified interfaces. (But see the discussion of class-based overrides for exceptions.)
  62  * </p><p>
  63  * The adapter class is generated in a new secure class loader that inherits Nashorn's protection domain, and has either
  64  * one of the original types' class loader or the Nashorn's class loader as its parent - the parent class loader
  65  * is chosen so that all the original types and the Nashorn core classes are visible from it (as the adapter will have
  66  * constant pool references to ScriptObject and ScriptFunction classes). In case none of the candidate class loaders has
  67  * visibility of all the required types, an error is thrown. The class uses {@link JavaAdapterBytecodeGenerator} to
  68  * generate the adapter class itself; see its documentation for details about the generated class.
  69  * </p><p>
  70  * You normally don't use this class directly, but rather either create adapters from script using
  71  * {@link NativeJava#extend(Object, Object...)}, using the {@code new} operator on abstract classes and interfaces (see
  72  * {@link NativeJava#type(Object, Object)}), or implicitly when passing script functions to Java methods expecting SAM
  73  * types.
  74  * </p>
  75  */
  76 
  77 @SuppressWarnings("javadoc")
  78 public final class JavaAdapterFactory {
  79     private static final ProtectionDomain MINIMAL_PERMISSION_DOMAIN = createMinimalPermissionDomain();
  80 
  81     // context with permissions needs for AdapterInfo creation
  82     private static final AccessControlContext CREATE_ADAPTER_INFO_ACC_CTXT =
  83         ClassAndLoader.createPermAccCtxt("createClassLoader", "getClassLoader",
  84             "accessDeclaredMembers", "accessClassInPackage.jdk.nashorn.internal.runtime");
  85 
  86     /**
  87      * A mapping from an original Class object to AdapterInfo representing the adapter for the class it represents.
  88      */
  89     private static final ClassValue<Map<List<Class<?>>, AdapterInfo>> ADAPTER_INFO_MAPS = new ClassValue<Map<List<Class<?>>, AdapterInfo>>() {
  90         @Override
  91         protected Map<List<Class<?>>, AdapterInfo> computeValue(final Class<?> type) {
  92             return new HashMap<>();
  93         }
  94     };
  95 
  96     /**
  97      * Returns an adapter class for the specified original types. The adapter class extends/implements the original
  98      * class/interfaces.
  99      * @param types the original types. The caller must pass at least one Java type representing either a public
 100      * interface or a non-final public class with at least one public or protected constructor. If more than one type is
 101      * specified, at most one can be a class and the rest have to be interfaces. The class can be in any position in the
 102      * array. Invoking the method twice with exactly the same types in the same order will return the same adapter
 103      * class, any reordering of types or even addition or removal of redundant types (i.e. interfaces that other types
 104      * in the list already implement/extend, or {@code java.lang.Object} in a list of types consisting purely of
 105      * interfaces) will result in a different adapter class, even though those adapter classes are functionally
 106      * identical; we deliberately don't want to incur the additional processing cost of canonicalizing type lists.
 107      * @param classOverrides a JavaScript object with functions serving as the class-level overrides and
 108      * implementations. These overrides are defined for all instances of the class, and can be further overridden on a
 109      * per-instance basis by passing additional objects in the constructor.
 110      * @param lookup the lookup object identifying the caller class. The generated adapter class will have the
 111      * protection domain of the caller class iff the lookup object is full-strength, otherwise it will be completely
 112      * unprivileged.
 113      * @return an adapter class. See this class' documentation for details on the generated adapter class.
 114      * @throws ECMAException with a TypeError if the adapter class can not be generated because the original class is
 115      * final, non-public, or has no public or protected constructors.
 116      */
 117     public static StaticClass getAdapterClassFor(final Class<?>[] types, ScriptObject classOverrides, final MethodHandles.Lookup lookup) {
 118         return getAdapterClassFor(types, classOverrides, getProtectionDomain(lookup));
 119     }
 120 
 121     private static StaticClass getAdapterClassFor(final Class<?>[] types, ScriptObject classOverrides, final ProtectionDomain protectionDomain) {
 122         assert types != null && types.length > 0;
 123         final SecurityManager sm = System.getSecurityManager();
 124         if (sm != null) {
 125             for (Class<?> type : types) {
 126                 // check for restricted package access
 127                 Context.checkPackageAccess(type);
 128                 // check for classes, interfaces in reflection
 129                 ReflectionCheckLinker.checkReflectionAccess(type, true);
 130             }
 131         }
 132         return getAdapterInfo(types).getAdapterClass(classOverrides, protectionDomain);
 133     }
 134 
 135     private static ProtectionDomain getProtectionDomain(final MethodHandles.Lookup lookup) {
 136         if((lookup.lookupModes() & Lookup.PRIVATE) == 0) {
 137             return MINIMAL_PERMISSION_DOMAIN;
 138         }
 139         return getProtectionDomain(lookup.lookupClass());
 140     }
 141 
 142     private static ProtectionDomain getProtectionDomain(final Class<?> clazz) {
 143         return AccessController.doPrivileged(new PrivilegedAction<ProtectionDomain>() {
 144             @Override
 145             public ProtectionDomain run() {
 146                 return clazz.getProtectionDomain();
 147             }
 148         });
 149     }
 150 
 151     /**
 152      * Returns a method handle representing a constructor that takes a single argument of the source type (which,
 153      * really, should be one of {@link ScriptObject}, {@link ScriptFunction}, or {@link Object}, and returns an instance
 154      * of the adapter for the target type. Used to implement the function autoconverters as well as the Nashorn's
 155      * JSR-223 script engine's {@code getInterface()} method.
 156      * @param sourceType the source type; should be either {@link ScriptObject}, {@link ScriptFunction}, or
 157      * {@link Object}. In case of {@code Object}, it will return a method handle that dispatches to either the script
 158      * object or function constructor at invocation based on the actual argument.
 159      * @param targetType the target type, for which adapter instances will be created
 160      * @return the constructor method handle.
 161      * @throws Exception if anything goes wrong
 162      */
 163     public static MethodHandle getConstructor(final Class<?> sourceType, final Class<?> targetType, final MethodHandles.Lookup lookup) throws Exception {
 164         final StaticClass adapterClass = getAdapterClassFor(new Class<?>[] { targetType }, null, lookup);
 165         return MH.bindTo(Bootstrap.getLinkerServices().getGuardedInvocation(new LinkRequestImpl(
 166                 NashornCallSiteDescriptor.get(lookup, "dyn:new",
 167                         MethodType.methodType(targetType, StaticClass.class, sourceType), 0), false,
 168                         adapterClass, null)).getInvocation(), adapterClass);
 169     }
 170 
 171     /**
 172      * Returns whether an instance of the specified class/interface can be generated from a ScriptFunction. Returns true
 173      * iff: the adapter for the class/interface can be created, it is abstract (this includes interfaces), it has at
 174      * least one abstract method, all the abstract methods share the same name, and it has a public or protected default
 175      * constructor. Note that invoking this class will most likely result in the adapter class being defined in the JVM
 176      * if it hasn't been already.
 177      * @param clazz the inspected class
 178      * @return true iff an instance of the specified class/interface can be generated from a ScriptFunction.
 179      */
 180     static boolean isAutoConvertibleFromFunction(final Class<?> clazz) {
 181         return getAdapterInfo(new Class<?>[] { clazz }).autoConvertibleFromFunction;
 182     }
 183 
 184     private static AdapterInfo getAdapterInfo(final Class<?>[] types) {
 185         final ClassAndLoader definingClassAndLoader = ClassAndLoader.getDefiningClassAndLoader(types);
 186 
 187         final Map<List<Class<?>>, AdapterInfo> adapterInfoMap = ADAPTER_INFO_MAPS.get(definingClassAndLoader.getRepresentativeClass());
 188         final List<Class<?>> typeList = types.length == 1 ? getSingletonClassList(types[0]) : Arrays.asList(types.clone());
 189         AdapterInfo adapterInfo;
 190         synchronized(adapterInfoMap) {
 191             adapterInfo = adapterInfoMap.get(typeList);
 192             if(adapterInfo == null) {
 193                 adapterInfo = createAdapterInfo(types, definingClassAndLoader);
 194                 adapterInfoMap.put(typeList, adapterInfo);
 195             }
 196         }
 197         return adapterInfo;
 198     }
 199 
 200     @SuppressWarnings({ "unchecked", "rawtypes" })
 201     private static List<Class<?>> getSingletonClassList(final Class<?> clazz) {
 202         return (List)Collections.singletonList(clazz);
 203     }
 204 
 205    /**
 206      * For a given class, create its adapter class and associated info.
 207      * @param type the class for which the adapter is created
 208      * @return the adapter info for the class.
 209      */
 210     private static AdapterInfo createAdapterInfo(final Class<?>[] types, final ClassAndLoader definingClassAndLoader) {
 211         Class<?> superClass = null;
 212         final List<Class<?>> interfaces = new ArrayList<>(types.length);
 213         for(final Class<?> t: types) {
 214             final int mod = t.getModifiers();
 215             if(!t.isInterface()) {
 216                 if(superClass != null) {
 217                     return new AdapterInfo(AdaptationResult.Outcome.ERROR_MULTIPLE_SUPERCLASSES, t.getCanonicalName() + " and " + superClass.getCanonicalName());
 218                 }
 219                 if (Modifier.isFinal(mod)) {
 220                     return new AdapterInfo(AdaptationResult.Outcome.ERROR_FINAL_CLASS, t.getCanonicalName());
 221                 }
 222                 superClass = t;
 223             } else {
 224                 if (interfaces.size() > 65535) {
 225                     throw new IllegalArgumentException("interface limit exceeded");
 226                 }
 227 
 228                 interfaces.add(t);
 229             }
 230 
 231             if(!Modifier.isPublic(mod)) {
 232                 return new AdapterInfo(AdaptationResult.Outcome.ERROR_NON_PUBLIC_CLASS, t.getCanonicalName());
 233             }
 234         }
 235 
 236 
 237         final Class<?> effectiveSuperClass = superClass == null ? Object.class : superClass;
 238         return AccessController.doPrivileged(new PrivilegedAction<AdapterInfo>() {
 239             @Override
 240             public AdapterInfo run() {
 241                 try {
 242                     return new AdapterInfo(effectiveSuperClass, interfaces, definingClassAndLoader);
 243                 } catch (final AdaptationException e) {
 244                     return new AdapterInfo(e.getAdaptationResult());
 245                 }
 246             }
 247         }, CREATE_ADAPTER_INFO_ACC_CTXT);
 248     }
 249 
 250     private static class AdapterInfo {
 251         private static final ClassAndLoader SCRIPT_OBJECT_LOADER = new ClassAndLoader(ScriptObject.class, true);
 252 
 253         private final ClassLoader commonLoader;
 254         // TODO: soft reference the JavaAdapterClassLoader objects. They can be recreated when needed.
 255         private final JavaAdapterClassLoader classAdapterGenerator;
 256         private final JavaAdapterClassLoader instanceAdapterGenerator;
 257         private final Map<CodeSource, StaticClass> instanceAdapters = new ConcurrentHashMap<>();
 258         final boolean autoConvertibleFromFunction;
 259         final AdaptationResult adaptationResult;
 260 
 261         AdapterInfo(Class<?> superClass, List<Class<?>> interfaces, ClassAndLoader definingLoader) throws AdaptationException {
 262             this.commonLoader = findCommonLoader(definingLoader);
 263             final JavaAdapterBytecodeGenerator gen = new JavaAdapterBytecodeGenerator(superClass, interfaces, commonLoader, false);
 264             this.autoConvertibleFromFunction = gen.isAutoConvertibleFromFunction();
 265             instanceAdapterGenerator = gen.createAdapterClassLoader();
 266             this.classAdapterGenerator = new JavaAdapterBytecodeGenerator(superClass, interfaces, commonLoader, true).createAdapterClassLoader();
 267             this.adaptationResult = AdaptationResult.SUCCESSFUL_RESULT;
 268         }
 269 
 270         AdapterInfo(final AdaptationResult.Outcome outcome, final String classList) {
 271             this(new AdaptationResult(outcome, classList));
 272         }
 273 
 274         AdapterInfo(final AdaptationResult adaptationResult) {
 275             this.commonLoader = null;
 276             this.classAdapterGenerator = null;
 277             this.instanceAdapterGenerator = null;
 278             this.autoConvertibleFromFunction = false;
 279             this.adaptationResult = adaptationResult;
 280         }
 281 
 282         StaticClass getAdapterClass(final ScriptObject classOverrides, final ProtectionDomain protectionDomain) {
 283             if(adaptationResult.getOutcome() != AdaptationResult.Outcome.SUCCESS) {
 284                 throw adaptationResult.typeError();
 285             }
 286             return classOverrides == null ? getInstanceAdapterClass(protectionDomain) :
 287                 getClassAdapterClass(classOverrides, protectionDomain);
 288         }
 289 
 290         private StaticClass getInstanceAdapterClass(final ProtectionDomain protectionDomain) {
 291             CodeSource codeSource = protectionDomain.getCodeSource();
 292             if(codeSource == null) {
 293                 codeSource = MINIMAL_PERMISSION_DOMAIN.getCodeSource();
 294             }
 295             StaticClass instanceAdapterClass = instanceAdapters.get(codeSource);
 296             if(instanceAdapterClass != null) {
 297                 return instanceAdapterClass;
 298             }
 299             // Any "unknown source" code source will default to no permission domain.
 300             final ProtectionDomain effectiveDomain = codeSource.equals(MINIMAL_PERMISSION_DOMAIN.getCodeSource()) ?
 301                     MINIMAL_PERMISSION_DOMAIN : protectionDomain;
 302 
 303             instanceAdapterClass = instanceAdapterGenerator.generateClass(commonLoader, effectiveDomain);
 304             final StaticClass existing = instanceAdapters.putIfAbsent(codeSource, instanceAdapterClass);
 305             return existing == null ? instanceAdapterClass : existing;
 306         }
 307 
 308         private StaticClass getClassAdapterClass(final ScriptObject classOverrides, final ProtectionDomain protectionDomain) {
 309             JavaAdapterServices.setClassOverrides(classOverrides);
 310             try {
 311                 return classAdapterGenerator.generateClass(commonLoader, protectionDomain);
 312             } finally {
 313                 JavaAdapterServices.setClassOverrides(null);
 314             }
 315         }
 316 
 317         /**
 318          * Choose between the passed class loader and the class loader that defines the ScriptObject class, based on which
 319          * of the two can see the classes in both.
 320          * @param classAndLoader the loader and a representative class from it that will be used to add the generated
 321          * adapter to its ADAPTER_INFO_MAPS.
 322          * @return the class loader that sees both the specified class and Nashorn classes.
 323          * @throws IllegalStateException if no such class loader is found.
 324          */
 325         private static ClassLoader findCommonLoader(final ClassAndLoader classAndLoader) throws AdaptationException {
 326             if(classAndLoader.canSee(SCRIPT_OBJECT_LOADER)) {
 327                 return classAndLoader.getLoader();
 328             }
 329             if (SCRIPT_OBJECT_LOADER.canSee(classAndLoader)) {
 330                 return SCRIPT_OBJECT_LOADER.getLoader();
 331             }
 332 
 333             throw new AdaptationException(AdaptationResult.Outcome.ERROR_NO_COMMON_LOADER, classAndLoader.getRepresentativeClass().getCanonicalName());
 334         }
 335     }
 336 
 337     private static ProtectionDomain createMinimalPermissionDomain() {
 338         // Generated classes need to have at least the permission to access Nashorn runtime and runtime.linker packages.
 339         final Permissions permissions = new Permissions();
 340         permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.runtime"));
 341         permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.runtime.linker"));
 342         return new ProtectionDomain(new CodeSource(null, (CodeSigner[])null), permissions);
 343     }
 344 }