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 java.lang.reflect.InvocationTargetException;
  29 import java.lang.reflect.Method;
  30 import java.security.AccessControlContext;
  31 import java.security.AccessController;
  32 import java.security.PrivilegedAction;
  33 import java.security.ProtectionDomain;
  34 import java.security.SecureClassLoader;
  35 import java.util.Arrays;
  36 import java.util.Collection;
  37 import java.util.Collections;
  38 import java.util.HashSet;
  39 import java.util.Set;
  40 import jdk.dynalink.beans.StaticClass;
  41 import jdk.nashorn.internal.codegen.DumpBytecode;
  42 import jdk.nashorn.internal.runtime.Context;
  43 import jdk.nashorn.internal.runtime.JSType;
  44 import jdk.nashorn.internal.runtime.ScriptFunction;
  45 import jdk.nashorn.internal.runtime.ScriptObject;
  46 
  47 /**
  48  * This class encapsulates the bytecode of the adapter class and can be used to load it into the JVM as an actual Class.
  49  * It can be invoked repeatedly to create multiple adapter classes from the same bytecode; adapter classes that have
  50  * class-level overrides must be re-created for every set of such overrides. Note that while this class is named
  51  * "class loader", it does not, in fact, extend {@code ClassLoader}, but rather uses them internally. Instances of this
  52  * class are normally created by {@code JavaAdapterBytecodeGenerator}.
  53  */
  54 final class JavaAdapterClassLoader {
  55     private static final Module NASHORN_MODULE = Context.class.getModule();
  56 
  57     private static final AccessControlContext CREATE_LOADER_ACC_CTXT = ClassAndLoader.createPermAccCtxt("createClassLoader");
  58     private static final AccessControlContext GET_CONTEXT_ACC_CTXT = ClassAndLoader.createPermAccCtxt(Context.NASHORN_GET_CONTEXT);
  59 
  60     private static final Collection<String> VISIBLE_INTERNAL_CLASS_NAMES = Collections.unmodifiableCollection(new HashSet<>(
  61             Arrays.asList(JavaAdapterServices.class.getName(), ScriptObject.class.getName(), ScriptFunction.class.getName(), JSType.class.getName())));
  62 
  63     private final String className;
  64     private final byte[] classBytes;
  65 
  66     JavaAdapterClassLoader(final String className, final byte[] classBytes) {
  67         this.className = className.replace('/', '.');
  68         this.classBytes = classBytes;
  69     }
  70 
  71     /**
  72      * Loads the generated adapter class into the JVM.
  73      * @param parentLoader the parent class loader for the generated class loader
  74      * @param protectionDomain the protection domain for the generated class
  75      * @return the generated adapter class
  76      */
  77     StaticClass generateClass(final ClassLoader parentLoader, final ProtectionDomain protectionDomain) {
  78         assert protectionDomain != null;
  79         return AccessController.doPrivileged(new PrivilegedAction<StaticClass>() {
  80             @Override
  81             public StaticClass run() {
  82                 try {
  83                     return StaticClass.forClass(Class.forName(className, true, createClassLoader(parentLoader, protectionDomain)));
  84                 } catch (final ClassNotFoundException e) {
  85                     throw new AssertionError(e); // cannot happen
  86                 }
  87             }
  88         }, CREATE_LOADER_ACC_CTXT);
  89     }
  90 
  91     // Note that the adapter class is created in the protection domain of the class/interface being
  92     // extended/implemented, and only the privileged global setter action class is generated in the protection domain
  93     // of Nashorn itself. Also note that the creation and loading of the global setter is deferred until it is
  94     // required by JVM linker, which will only happen on first invocation of any of the adapted method. We could defer
  95     // it even more by separating its invocation into a separate static method on the adapter class, but then someone
  96     // with ability to introspect on the class and use setAccessible(true) on it could invoke the method. It's a
  97     // security tradeoff...
  98     private ClassLoader createClassLoader(final ClassLoader parentLoader, final ProtectionDomain protectionDomain) {
  99         return new SecureClassLoader(parentLoader) {
 100             private final ClassLoader myLoader = getClass().getClassLoader();
 101 
 102             // the unnamed module into which adapter is loaded!
 103             private final Module adapterModule = getUnnamedModule();
 104 
 105             {
 106                 // specific exports from nashorn to the new adapter module
 107                 NASHORN_MODULE.addExports("jdk.nashorn.internal.runtime", adapterModule);
 108                 NASHORN_MODULE.addExports("jdk.nashorn.internal.runtime.linker", adapterModule);
 109 
 110                 // nashorn should be be able to read methods of classes loaded in adapter module
 111                 NASHORN_MODULE.addReads(adapterModule);
 112             }
 113 
 114             @Override
 115             public Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
 116                 try {
 117                     final int i = name.lastIndexOf('.');
 118                     if(i != -1){
 119                         final String pkgName = name.substring(0,i);
 120                         Context.checkPackageAccess(pkgName);
 121                     }
 122                     return super.loadClass(name, resolve);
 123                 } catch (final SecurityException se) {
 124                     // we may be implementing an interface or extending a class that was
 125                     // loaded by a loader that prevents package.access. If so, it'd throw
 126                     // SecurityException for nashorn's classes!. For adapter's to work, we
 127                     // should be able to refer to the few classes it needs in its implementation.
 128                     if(VISIBLE_INTERNAL_CLASS_NAMES.contains(name)) {
 129                         return myLoader != null? myLoader.loadClass(name) : Class.forName(name, false, myLoader);
 130                     }
 131                     throw se;
 132                 }
 133             }
 134 
 135             @Override
 136             protected Class<?> findClass(final String name) throws ClassNotFoundException {
 137                 if(name.equals(className)) {
 138                     assert classBytes != null : "what? already cleared .class bytes!!";
 139 
 140                     final Context ctx = AccessController.doPrivileged(new PrivilegedAction<Context>() {
 141                         @Override
 142                         public Context run() {
 143                             return Context.getContext();
 144                         }
 145                     }, GET_CONTEXT_ACC_CTXT);
 146                     DumpBytecode.dumpBytecode(ctx.getEnv(), ctx.getLogger(jdk.nashorn.internal.codegen.Compiler.class), classBytes, name);
 147                     return defineClass(name, classBytes, 0, classBytes.length, protectionDomain);
 148                 }
 149                 throw new ClassNotFoundException(name);
 150             }
 151         };
 152     }
 153 }