/* * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.module.Configuration; import java.lang.module.ModuleReference; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor.Exports; import java.lang.module.ModuleDescriptor.Opens; import java.lang.module.ModuleDescriptor.Version; import java.lang.module.ResolvedModule; import java.lang.reflect.AnnotatedElement; import java.net.URI; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.internal.loader.BuiltinClassLoader; import jdk.internal.loader.BootLoader; import jdk.internal.loader.ClassLoaders; import jdk.internal.module.IllegalAccessLogger; import jdk.internal.module.ModuleLoaderMap; import jdk.internal.module.ServicesCatalog; import jdk.internal.module.Resources; import jdk.internal.org.objectweb.asm.AnnotationVisitor; import jdk.internal.org.objectweb.asm.Attribute; import jdk.internal.org.objectweb.asm.ClassReader; import jdk.internal.org.objectweb.asm.ClassVisitor; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.ModuleVisitor; import jdk.internal.org.objectweb.asm.Opcodes; import jdk.internal.reflect.CallerSensitive; import jdk.internal.reflect.Reflection; import sun.security.util.SecurityConstants; /** * Represents a run-time module, either {@link #isNamed() named} or unnamed. * *
Named modules have a {@link #getName() name} and are constructed by the * Java Virtual Machine when a graph of modules is defined to the Java virtual * machine to create a {@linkplain ModuleLayer module layer}.
* *An unnamed module does not have a name. There is an unnamed module for * each {@link ClassLoader ClassLoader}, obtained by invoking its {@link * ClassLoader#getUnnamedModule() getUnnamedModule} method. All types that are * not in a named module are members of their defining class loader's unnamed * module.
* *The package names that are parameters or returned by methods defined in * this class are the fully-qualified names of the packages as defined in * section 6.5.3 of The Java™ Language Specification, for * example, {@code "java.lang"}.
* *Unless otherwise specified, passing a {@code null} argument to a method * in this class causes a {@link NullPointerException NullPointerException} to * be thrown.
* * @since 9 * @spec JPMS * @see Class#getModule() */ public final class Module implements AnnotatedElement { // the layer that contains this module, can be null private final ModuleLayer layer; // module name and loader, these fields are read by VM private final String name; private final ClassLoader loader; // the module descriptor private final ModuleDescriptor descriptor; /** * Creates a new named Module. The resulting Module will be defined to the * VM but will not read any other modules, will not have any exports setup * and will not be registered in the service catalog. */ Module(ModuleLayer layer, ClassLoader loader, ModuleDescriptor descriptor, URI uri) { this.layer = layer; this.name = descriptor.name(); this.loader = loader; this.descriptor = descriptor; // define module to VM boolean isOpen = descriptor.isOpen() || descriptor.isAutomatic(); Version version = descriptor.version().orElse(null); String vs = Objects.toString(version, null); String loc = Objects.toString(uri, null); String[] packages = descriptor.packages().toArray(new String[0]); defineModule0(this, isOpen, vs, loc, packages); } /** * Create the unnamed Module for the given ClassLoader. * * @see ClassLoader#getUnnamedModule */ Module(ClassLoader loader) { this.layer = null; this.name = null; this.loader = loader; this.descriptor = null; } /** * Creates a named module but without defining the module to the VM. * * @apiNote This constructor is for VM white-box testing. */ Module(ClassLoader loader, ModuleDescriptor descriptor) { this.layer = null; this.name = descriptor.name(); this.loader = loader; this.descriptor = descriptor; } /** * Returns {@code true} if this module is a named module. * * @return {@code true} if this is a named module * * @see ClassLoader#getUnnamedModule() */ public boolean isNamed() { return name != null; } /** * Returns the module name or {@code null} if this module is an unnamed * module. * * @return The module name */ public String getName() { return name; } /** * Returns the {@code ClassLoader} for this module. * *If there is a security manager then its {@code checkPermission} * method if first called with a {@code RuntimePermission("getClassLoader")} * permission to check that the caller is allowed to get access to the * class loader.
* * @return The class loader for this module * * @throws SecurityException * If denied by the security manager */ public ClassLoader getClassLoader() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); } return loader; } /** * Returns the module descriptor for this module or {@code null} if this * module is an unnamed module. * * @return The module descriptor for this module */ public ModuleDescriptor getDescriptor() { return descriptor; } /** * Returns the module layer that contains this module or {@code null} if * this module is not in a module layer. * * A module layer contains named modules and therefore this method always * returns {@code null} when invoked on an unnamed module. * *Dynamic modules are * named modules that are generated at runtime. A dynamic module may or may * not be in a module layer.
* * @return The module layer that contains this module * * @see java.lang.reflect.Proxy */ public ModuleLayer getLayer() { if (isNamed()) { ModuleLayer layer = this.layer; if (layer != null) return layer; // special-case java.base as it is created before the boot layer if (loader == null && name.equals("java.base")) { return ModuleLayer.boot(); } } return null; } // -- // special Module to mean "all unnamed modules" private static final Module ALL_UNNAMED_MODULE = new Module(null); private static final SetThis method returns {@code true} if invoked to test if a package in * this module is exported to itself. It always returns {@code true} when * invoked on an unnamed module. A package that is {@link #isOpen open} to * the given module is considered exported to that module at run-time and * so this method returns {@code true} if the package is open to the given * module.
* *This method does not check if the given module reads this module.
* * @param pn * The package name * @param other * The other module * * @return {@code true} if this module exports the package to at least the * given module * * @see ModuleDescriptor#exports() * @see #addExports(String,Module) */ public boolean isExported(String pn, Module other) { Objects.requireNonNull(pn); Objects.requireNonNull(other); return implIsExportedOrOpen(pn, other, /*open*/false); } /** * Returns {@code true} if this module has opened a package to at * least the given module. * *This method returns {@code true} if invoked to test if a package in * this module is open to itself. It returns {@code true} when invoked on an * {@link ModuleDescriptor#isOpen open} module with a package in the module. * It always returns {@code true} when invoked on an unnamed module.
* *This method does not check if the given module reads this module.
* * @param pn * The package name * @param other * The other module * * @return {@code true} if this module has opened the package * to at least the given module * * @see ModuleDescriptor#opens() * @see #addOpens(String,Module) * @see java.lang.reflect.AccessibleObject#setAccessible(boolean) * @see java.lang.invoke.MethodHandles#privateLookupIn */ public boolean isOpen(String pn, Module other) { Objects.requireNonNull(pn); Objects.requireNonNull(other); return implIsExportedOrOpen(pn, other, /*open*/true); } /** * Returns {@code true} if this module exports the given package * unconditionally. * *This method always returns {@code true} when invoked on an unnamed * module. A package that is {@link #isOpen(String) opened} unconditionally * is considered exported unconditionally at run-time and so this method * returns {@code true} if the package is opened unconditionally.
* *This method does not check if the given module reads this module.
* * @param pn * The package name * * @return {@code true} if this module exports the package unconditionally * * @see ModuleDescriptor#exports() */ public boolean isExported(String pn) { Objects.requireNonNull(pn); return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/false); } /** * Returns {@code true} if this module has opened a package * unconditionally. * *This method always returns {@code true} when invoked on an unnamed * module. Additionally, it always returns {@code true} when invoked on an * {@link ModuleDescriptor#isOpen open} module with a package in the * module.
* *This method does not check if the given module reads this module.
* * @param pn * The package name * * @return {@code true} if this module has opened the package * unconditionally * * @see ModuleDescriptor#opens() */ public boolean isOpen(String pn) { Objects.requireNonNull(pn); return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/true); } /** * Returns {@code true} if this module exports or opens the given package * to the given module. If the other module is {@code EVERYONE_MODULE} then * this method tests if the package is exported or opened unconditionally. */ private boolean implIsExportedOrOpen(String pn, Module other, boolean open) { // all packages in unnamed modules are open if (!isNamed()) return true; // all packages are exported/open to self if (other == this && descriptor.packages().contains(pn)) return true; // all packages in open and automatic modules are open if (descriptor.isOpen() || descriptor.isAutomatic()) return descriptor.packages().contains(pn); // exported/opened via module declaration/descriptor if (isStaticallyExportedOrOpen(pn, other, open)) return true; // exported via addExports/addOpens if (isReflectivelyExportedOrOpen(pn, other, open)) return true; // not exported or open to other return false; } /** * Returns {@code true} if this module exports or opens a package to * the given module via its module declaration or CLI options. */ private boolean isStaticallyExportedOrOpen(String pn, Module other, boolean open) { // test if package is open to everyone orThis method has no effect if the package is already exported (or * open) to the given module.
* * @apiNote As specified in section 5.4.3 of the The Java™ * Virtual Machine Specification , if an attempt to resolve a * symbolic reference fails because of a linkage error, then subsequent * attempts to resolve the reference always fail with the same error that * was thrown as a result of the initial resolution attempt. * * @param pn * The package name * @param other * The module * * @return this module * * @throws IllegalArgumentException * If {@code pn} is {@code null}, or this is a named module and the * package {@code pn} is not a package in this module * @throws IllegalCallerException * If this is a named module and the caller's module is not this * module * * @jvms 5.4.3 Resolution * @see #isExported(String,Module) */ @CallerSensitive public Module addExports(String pn, Module other) { if (pn == null) throw new IllegalArgumentException("package is null"); Objects.requireNonNull(other); if (isNamed()) { Module caller = getCallerModule(Reflection.getCallerClass()); if (caller != this) { throw new IllegalCallerException(caller + " != " + this); } implAddExportsOrOpens(pn, other, /*open*/false, /*syncVM*/true); } return this; } /** * If this module has opened a package to at least the caller * module then update this module to open the package to the given module. * Opening a package with this method allows all types in the package, * and all their members, not just public types and their public members, * to be reflected on by the given module when using APIs that support * private access or a way to bypass or suppress default Java language * access control checks. * *This method has no effect if the package is already open * to the given module.
* * @apiNote This method can be used for cases where a consumer * module uses a qualified opens to open a package to an API * module but where the reflective access to the members of classes in * the consumer module is delegated to code in another module. Code in the * API module can use this method to open the package in the consumer module * to the other module. * * @param pn * The package name * @param other * The module * * @return this module * * @throws IllegalArgumentException * If {@code pn} is {@code null}, or this is a named module and the * package {@code pn} is not a package in this module * @throws IllegalCallerException * If this is a named module and this module has not opened the * package to at least the caller's module * * @see #isOpen(String,Module) * @see java.lang.reflect.AccessibleObject#setAccessible(boolean) * @see java.lang.invoke.MethodHandles#privateLookupIn */ @CallerSensitive public Module addOpens(String pn, Module other) { if (pn == null) throw new IllegalArgumentException("package is null"); Objects.requireNonNull(other); if (isNamed()) { Module caller = getCallerModule(Reflection.getCallerClass()); if (caller != this && (caller == null || !isOpen(pn, caller))) throw new IllegalCallerException(pn + " is not open to " + caller); implAddExportsOrOpens(pn, other, /*open*/true, /*syncVM*/true); } return this; } /** * Updates this module to export a package unconditionally. * * @apiNote This method is for JDK tests only. */ void implAddExports(String pn) { implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, false, true); } /** * Updates this module to export a package to another module. * * @apiNote Used by Instrumentation::redefineModule and --add-exports */ void implAddExports(String pn, Module other) { implAddExportsOrOpens(pn, other, false, true); } /** * Updates this module to export a package to all unnamed modules. * * @apiNote Used by the --add-exports command line option. */ void implAddExportsToAllUnnamed(String pn) { implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, false, true); } /** * Updates this export to export a package unconditionally without * notifying the VM. * * @apiNote This method is for VM white-box testing. */ void implAddExportsNoSync(String pn) { implAddExportsOrOpens(pn.replace('/', '.'), Module.EVERYONE_MODULE, false, false); } /** * Updates a module to export a package to another module without * notifying the VM. * * @apiNote This method is for VM white-box testing. */ void implAddExportsNoSync(String pn, Module other) { implAddExportsOrOpens(pn.replace('/', '.'), other, false, false); } /** * Updates this module to open a package unconditionally. * * @apiNote This method is for JDK tests only. */ void implAddOpens(String pn) { implAddExportsOrOpens(pn, Module.EVERYONE_MODULE, true, true); } /** * Updates this module to open a package to another module. * * @apiNote Used by Instrumentation::redefineModule and --add-opens */ void implAddOpens(String pn, Module other) { implAddExportsOrOpens(pn, other, true, true); } /** * Updates this module to open a package to all unnamed modules. * * @apiNote Used by the --add-opens command line option. */ void implAddOpensToAllUnnamed(String pn) { implAddExportsOrOpens(pn, Module.ALL_UNNAMED_MODULE, true, true); } /** * Updates a module to export or open a module to another module. * * If {@code syncVM} is {@code true} then the VM is notified. */ private void implAddExportsOrOpens(String pn, Module other, boolean open, boolean syncVM) { Objects.requireNonNull(other); Objects.requireNonNull(pn); // all packages are open in unnamed, open, and automatic modules if (!isNamed() || descriptor.isOpen() || descriptor.isAutomatic()) return; // check if the package is already exported/open to other if (implIsExportedOrOpen(pn, other, open)) { // if the package is exported/open for illegal access then we need // to record that it has also been exported/opened reflectively so // that the IllegalAccessLogger doesn't emit a warning. boolean needToAdd = false; if (!other.isNamed()) { IllegalAccessLogger l = IllegalAccessLogger.illegalAccessLogger(); if (l != null) { if (open) { needToAdd = l.isOpenForIllegalAccess(this, pn); } else { needToAdd = l.isExportedForIllegalAccess(this, pn); } } } if (!needToAdd) { // nothing to do return; } } // can only export a package in the module if (!descriptor.packages().contains(pn)) { throw new IllegalArgumentException("package " + pn + " not in contents"); } // update VM first, just in case it fails if (syncVM) { if (other == EVERYONE_MODULE) { addExportsToAll0(this, pn); } else if (other == ALL_UNNAMED_MODULE) { addExportsToAllUnnamed0(this, pn); } else { addExports0(this, pn, other); } } // add package name to exports if absent MapThis method does not cause {@link Configuration#resolveAndBind * resolveAndBind} to be re-run.
* * @param service * The service type * * @return this module * * @throws IllegalCallerException * If this is a named module and the caller's module is not this * module * * @see #canUse(Class) * @see ModuleDescriptor#uses() */ @CallerSensitive public Module addUses(Class> service) { Objects.requireNonNull(service); if (isNamed() && !descriptor.isAutomatic()) { Module caller = getCallerModule(Reflection.getCallerClass()); if (caller != this) { throw new IllegalCallerException(caller + " != " + this); } implAddUses(service); } return this; } /** * Update this module to add a service dependence on the given service * type. */ void implAddUses(Class> service) { if (!canUse(service)) { ReflectionData.uses.putIfAbsent(this, service, Boolean.TRUE); } } /** * Indicates if this module has a service dependence on the given service * type. This method always returns {@code true} when invoked on an unnamed * module or an automatic module. * * @param service * The service type * * @return {@code true} if this module uses service type {@code st} * * @see #addUses(Class) */ public boolean canUse(Class> service) { Objects.requireNonNull(service); if (!isNamed()) return true; if (descriptor.isAutomatic()) return true; // uses was declared if (descriptor.uses().contains(service.getName())) return true; // uses added via addUses return ReflectionData.uses.containsKeyPair(this, service); } // -- packages -- /** * Returns the set of package names for the packages in this module. * *For named modules, the returned set contains an element for each * package in the module.
* *For unnamed modules, this method is the equivalent to invoking the * {@link ClassLoader#getDefinedPackages() getDefinedPackages} method of * this module's class loader and returning the set of package names.
* * @return the set of the package names of the packages in this module */ public SetA resource in a named module may be encapsulated so that * it cannot be located by code in other modules. Whether a resource can be * located or not is determined as follows:
* *In the above, the package name for a resource is derived * from the subsequence of characters that precedes the last {@code '/'} in * the name and then replacing each {@code '/'} character in the subsequence * with {@code '.'}. A leading slash is ignored when deriving the package * name. As an example, the package name derived for a resource named * "{@code a/b/c/foo.properties}" is "{@code a.b.c}". A resource name * with the name "{@code META-INF/MANIFEST.MF}" is never encapsulated * because "{@code META-INF}" is not a legal package name.
* *This method returns {@code null} if the resource is not in this * module, the resource is encapsulated and cannot be located by the caller, * or access to the resource is denied by the security manager.
* * @param name * The resource name * * @return An input stream for reading the resource or {@code null} * * @throws IOException * If an I/O error occurs * * @see Class#getResourceAsStream(String) */ @CallerSensitive public InputStream getResourceAsStream(String name) throws IOException { if (name.startsWith("/")) { name = name.substring(1); } if (isNamed() && Resources.canEncapsulate(name)) { Module caller = getCallerModule(Reflection.getCallerClass()); if (caller != this && caller != Object.class.getModule()) { String pn = Resources.toPackageName(name); if (getPackages().contains(pn)) { if (caller == null && !isOpen(pn)) { // no caller, package not open return null; } if (!isOpen(pn, caller)) { // package not open to caller return null; } } } } String mn = this.name; // special-case built-in class loaders to avoid URL connection if (loader == null) { return BootLoader.findResourceAsStream(mn, name); } else if (loader instanceof BuiltinClassLoader) { return ((BuiltinClassLoader) loader).findResourceAsStream(mn, name); } // locate resource in module URL url = loader.findResource(mn, name); if (url != null) { try { return url.openStream(); } catch (SecurityException e) { } } return null; } /** * Returns the string representation of this module. For a named module, * the representation is the string {@code "module"}, followed by a space, * and then the module name. For an unnamed module, the representation is * the string {@code "unnamed module"}, followed by a space, and then an * implementation specific string that identifies the unnamed module. * * @return The string representation of this module */ @Override public String toString() { if (isNamed()) { return "module " + name; } else { String id = Integer.toHexString(System.identityHashCode(this)); return "unnamed module @" + id; } } /** * Returns the module that a given caller class is a member of. Returns * {@code null} if the caller is {@code null}. */ private Module getCallerModule(Class> caller) { return (caller != null) ? caller.getModule() : null; } // -- native methods -- // JVM_DefineModule private static native void defineModule0(Module module, boolean isOpen, String version, String location, String[] pns); // JVM_AddReadsModule private static native void addReads0(Module from, Module to); // JVM_AddModuleExports private static native void addExports0(Module from, String pn, Module to); // JVM_AddModuleExportsToAll private static native void addExportsToAll0(Module from, String pn); // JVM_AddModuleExportsToAllUnnamed private static native void addExportsToAllUnnamed0(Module from, String pn); }