JavaAdapterClassLoader.java revision 1709:39dececd7338
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package jdk.nashorn.internal.runtime.linker;
27
28import java.lang.module.ModuleDescriptor;
29import java.lang.reflect.InvocationTargetException;
30import java.lang.reflect.Method;
31import java.lang.reflect.Module;
32import java.security.AccessControlContext;
33import java.security.AccessController;
34import java.security.PrivilegedAction;
35import java.security.ProtectionDomain;
36import java.security.SecureClassLoader;
37import java.util.Arrays;
38import java.util.Collection;
39import java.util.Collections;
40import java.util.HashSet;
41import java.util.Set;
42import jdk.dynalink.beans.StaticClass;
43import jdk.nashorn.internal.codegen.DumpBytecode;
44import jdk.nashorn.internal.runtime.Context;
45import jdk.nashorn.internal.runtime.JSType;
46import jdk.nashorn.internal.runtime.ScriptFunction;
47import jdk.nashorn.internal.runtime.ScriptObject;
48
49/**
50 * This class encapsulates the bytecode of the adapter class and can be used to load it into the JVM as an actual Class.
51 * It can be invoked repeatedly to create multiple adapter classes from the same bytecode; adapter classes that have
52 * class-level overrides must be re-created for every set of such overrides. Note that while this class is named
53 * "class loader", it does not, in fact, extend {@code ClassLoader}, but rather uses them internally. Instances of this
54 * class are normally created by {@code JavaAdapterBytecodeGenerator}.
55 */
56final class JavaAdapterClassLoader {
57    private static final Module NASHORN_MODULE = Context.class.getModule();
58
59    private static final AccessControlContext CREATE_LOADER_ACC_CTXT = ClassAndLoader.createPermAccCtxt("createClassLoader");
60    private static final AccessControlContext GET_CONTEXT_ACC_CTXT = ClassAndLoader.createPermAccCtxt(Context.NASHORN_GET_CONTEXT);
61    private static final AccessControlContext CREATE_MODULE_ACC_CTXT = ClassAndLoader.createPermAccCtxt(Context.NASHORN_CREATE_MODULE);
62
63    private static final Collection<String> VISIBLE_INTERNAL_CLASS_NAMES = Collections.unmodifiableCollection(new HashSet<>(
64            Arrays.asList(JavaAdapterServices.class.getName(), ScriptObject.class.getName(), ScriptFunction.class.getName(), JSType.class.getName())));
65
66    private final String className;
67    private final byte[] classBytes;
68    private final Set<Module> accessedModules;
69
70    JavaAdapterClassLoader(final String className, final byte[] classBytes, final Set<Module> accessedModules) {
71        this.className = className.replace('/', '.');
72        this.classBytes = classBytes;
73        this.accessedModules = accessedModules;
74    }
75
76    /**
77     * Loads the generated adapter class into the JVM.
78     * @param parentLoader the parent class loader for the generated class loader
79     * @param protectionDomain the protection domain for the generated class
80     * @return the generated adapter class
81     */
82    StaticClass generateClass(final ClassLoader parentLoader, final ProtectionDomain protectionDomain) {
83        assert protectionDomain != null;
84        return AccessController.doPrivileged(new PrivilegedAction<StaticClass>() {
85            @Override
86            public StaticClass run() {
87                try {
88                    return StaticClass.forClass(Class.forName(className, true, createClassLoader(parentLoader, protectionDomain)));
89                } catch (final ClassNotFoundException e) {
90                    throw new AssertionError(e); // cannot happen
91                }
92            }
93        }, CREATE_LOADER_ACC_CTXT);
94    }
95
96    private static Module createAdapterModule(final ClassLoader loader) {
97        final ModuleDescriptor descriptor =
98            new ModuleDescriptor.Builder("jdk.scripting.nashorn.javaadapters")
99                .requires(NASHORN_MODULE.getName())
100                .exports(JavaAdapterBytecodeGenerator.ADAPTER_PACKAGE)
101                .build();
102
103        return AccessController.doPrivileged(new PrivilegedAction<Module>() {
104            @Override
105            public Module run() {
106                return Context.createModule(descriptor, loader);
107            }
108        }, CREATE_MODULE_ACC_CTXT);
109    }
110
111    // Note that the adapter class is created in the protection domain of the class/interface being
112    // extended/implemented, and only the privileged global setter action class is generated in the protection domain
113    // of Nashorn itself. Also note that the creation and loading of the global setter is deferred until it is
114    // required by JVM linker, which will only happen on first invocation of any of the adapted method. We could defer
115    // it even more by separating its invocation into a separate static method on the adapter class, but then someone
116    // with ability to introspect on the class and use setAccessible(true) on it could invoke the method. It's a
117    // security tradeoff...
118    private ClassLoader createClassLoader(final ClassLoader parentLoader, final ProtectionDomain protectionDomain) {
119        return new SecureClassLoader(parentLoader) {
120            private final ClassLoader myLoader = getClass().getClassLoader();
121
122            // new adapter module
123            private final Module adapterModule = createAdapterModule(this);
124
125            {
126                // new adapter module read-edges
127                if (!accessedModules.isEmpty()) {
128
129                    // There are modules accessed from this adapter. We need to add module-read
130                    // edges to those from the adapter module. We do this by generating a
131                    // package-private class, loading it with this adapter class loader and
132                    // then calling a private static method on it.
133                    final byte[] buf = JavaAdapterBytecodeGenerator.getModulesAddReadsBytes();
134                    final Class<?> addReader = defineClass(
135                        JavaAdapterBytecodeGenerator.MODULES_READ_ADDER, buf, 0, buf.length);
136                    final PrivilegedAction<Method> pa = () -> {
137                        try {
138                            final Method m = addReader.getDeclaredMethod(
139                                JavaAdapterBytecodeGenerator.MODULES_ADD_READS, Module[].class);
140                            m.setAccessible(true);
141                            return m;
142                        } catch (final NoSuchMethodException | SecurityException ex) {
143                            throw new RuntimeException(ex);
144                        }
145                    };
146                    final Method addReads = AccessController.doPrivileged(pa);
147                    try {
148                        addReads.invoke(null, (Object)accessedModules.toArray(new Module[0]));
149                    } catch (final IllegalAccessException | IllegalArgumentException |
150                            InvocationTargetException ex) {
151                        throw new RuntimeException(ex);
152                    }
153                }
154
155                // specific exports from nashorn to the new adapter module
156                NASHORN_MODULE.addExports("jdk.nashorn.internal.runtime", adapterModule);
157                NASHORN_MODULE.addExports("jdk.nashorn.internal.runtime.linker", adapterModule);
158
159                // nashorn should be be able to read methods of classes loaded in adapter module
160                NASHORN_MODULE.addReads(adapterModule);
161            }
162
163            @Override
164            public Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
165                try {
166                    Context.checkPackageAccess(name);
167                    return super.loadClass(name, resolve);
168                } catch (final SecurityException se) {
169                    // we may be implementing an interface or extending a class that was
170                    // loaded by a loader that prevents package.access. If so, it'd throw
171                    // SecurityException for nashorn's classes!. For adapter's to work, we
172                    // should be able to refer to the few classes it needs in its implementation.
173                    if(VISIBLE_INTERNAL_CLASS_NAMES.contains(name)) {
174                        return myLoader != null? myLoader.loadClass(name) : Class.forName(name, false, myLoader);
175                    }
176                    throw se;
177                }
178            }
179
180            @Override
181            protected Class<?> findClass(final String name) throws ClassNotFoundException {
182                if(name.equals(className)) {
183                    assert classBytes != null : "what? already cleared .class bytes!!";
184
185                    final Context ctx = AccessController.doPrivileged(new PrivilegedAction<Context>() {
186                        @Override
187                        public Context run() {
188                            return Context.getContext();
189                        }
190                    }, GET_CONTEXT_ACC_CTXT);
191                    DumpBytecode.dumpBytecode(ctx.getEnv(), ctx.getLogger(jdk.nashorn.internal.codegen.Compiler.class), classBytes, name);
192                    return defineClass(name, classBytes, 0, classBytes.length, protectionDomain);
193                }
194                throw new ClassNotFoundException(name);
195            }
196        };
197    }
198}
199