Path: blob/master/src/java.base/share/classes/java/lang/ClassLoader.java
41152 views
/*1* Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.2* Copyright (c) 2019, Azul Systems, Inc. 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 it6* under the terms of the GNU General Public License version 2 only, as7* published by the Free Software Foundation. Oracle designates this8* particular file as subject to the "Classpath" exception as provided9* 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 WITHOUT12* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or13* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License14* version 2 for more details (a copy is included in the LICENSE file that15* accompanied this code).16*17* You should have received a copy of the GNU General Public License version18* 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 USA22* or visit www.oracle.com if you need additional information or have any23* questions.24*/2526package java.lang;2728import java.io.InputStream;29import java.io.IOException;30import java.io.UncheckedIOException;31import java.io.File;32import java.lang.reflect.Constructor;33import java.lang.reflect.InvocationTargetException;34import java.net.URL;35import java.security.AccessController;36import java.security.AccessControlContext;37import java.security.CodeSource;38import java.security.PrivilegedAction;39import java.security.ProtectionDomain;40import java.security.cert.Certificate;41import java.util.ArrayList;42import java.util.Collections;43import java.util.Enumeration;44import java.util.HashMap;45import java.util.Map;46import java.util.NoSuchElementException;47import java.util.Objects;48import java.util.Set;49import java.util.Spliterator;50import java.util.Spliterators;51import java.util.WeakHashMap;52import java.util.concurrent.ConcurrentHashMap;53import java.util.function.Supplier;54import java.util.stream.Stream;55import java.util.stream.StreamSupport;5657import jdk.internal.loader.BootLoader;58import jdk.internal.loader.BuiltinClassLoader;59import jdk.internal.loader.ClassLoaders;60import jdk.internal.loader.NativeLibrary;61import jdk.internal.loader.NativeLibraries;62import jdk.internal.perf.PerfCounter;63import jdk.internal.misc.Unsafe;64import jdk.internal.misc.VM;65import jdk.internal.reflect.CallerSensitive;66import jdk.internal.reflect.Reflection;67import jdk.internal.util.StaticProperty;68import sun.reflect.misc.ReflectUtil;69import sun.security.util.SecurityConstants;7071/**72* A class loader is an object that is responsible for loading classes. The73* class {@code ClassLoader} is an abstract class. Given the <a74* href="#binary-name">binary name</a> of a class, a class loader should attempt to75* locate or generate data that constitutes a definition for the class. A76* typical strategy is to transform the name into a file name and then read a77* "class file" of that name from a file system.78*79* <p> Every {@link java.lang.Class Class} object contains a {@link80* Class#getClassLoader() reference} to the {@code ClassLoader} that defined81* it.82*83* <p> {@code Class} objects for array classes are not created by class84* loaders, but are created automatically as required by the Java runtime.85* The class loader for an array class, as returned by {@link86* Class#getClassLoader()} is the same as the class loader for its element87* type; if the element type is a primitive type, then the array class has no88* class loader.89*90* <p> Applications implement subclasses of {@code ClassLoader} in order to91* extend the manner in which the Java virtual machine dynamically loads92* classes.93*94* <p> Class loaders may typically be used by security managers to indicate95* security domains.96*97* <p> In addition to loading classes, a class loader is also responsible for98* locating resources. A resource is some data (a "{@code .class}" file,99* configuration data, or an image for example) that is identified with an100* abstract '/'-separated path name. Resources are typically packaged with an101* application or library so that they can be located by code in the102* application or library. In some cases, the resources are included so that103* they can be located by other libraries.104*105* <p> The {@code ClassLoader} class uses a delegation model to search for106* classes and resources. Each instance of {@code ClassLoader} has an107* associated parent class loader. When requested to find a class or108* resource, a {@code ClassLoader} instance will usually delegate the search109* for the class or resource to its parent class loader before attempting to110* find the class or resource itself.111*112* <p> Class loaders that support concurrent loading of classes are known as113* <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class114* loaders and are required to register themselves at their class initialization115* time by invoking the {@link116* #registerAsParallelCapable ClassLoader.registerAsParallelCapable}117* method. Note that the {@code ClassLoader} class is registered as parallel118* capable by default. However, its subclasses still need to register themselves119* if they are parallel capable.120* In environments in which the delegation model is not strictly121* hierarchical, class loaders need to be parallel capable, otherwise class122* loading can lead to deadlocks because the loader lock is held for the123* duration of the class loading process (see {@link #loadClass124* loadClass} methods).125*126* <h2> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h2>127*128* The Java run-time has the following built-in class loaders:129*130* <ul>131* <li><p>Bootstrap class loader.132* It is the virtual machine's built-in class loader, typically represented133* as {@code null}, and does not have a parent.</li>134* <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}.135* The platform class loader is responsible for loading the136* <em>platform classes</em>. Platform classes include Java SE platform APIs,137* their implementation classes and JDK-specific run-time classes that are138* defined by the platform class loader or its ancestors.139* The platform class loader can be used as the parent of a {@code ClassLoader}140* instance.141* <p> To allow for upgrading/overriding of modules defined to the platform142* class loader, and where upgraded modules read modules defined to class143* loaders other than the platform class loader and its ancestors, then144* the platform class loader may have to delegate to other class loaders,145* the application class loader for example.146* In other words, classes in named modules defined to class loaders147* other than the platform class loader and its ancestors may be visible148* to the platform class loader. </li>149* <li><p>{@linkplain #getSystemClassLoader() System class loader}.150* It is also known as <em>application class loader</em> and is distinct151* from the platform class loader.152* The system class loader is typically used to define classes on the153* application class path, module path, and JDK-specific tools.154* The platform class loader is the parent or an ancestor of the system class155* loader, so the system class loader can load platform classes by delegating156* to its parent.</li>157* </ul>158*159* <p> Normally, the Java virtual machine loads classes from the local file160* system in a platform-dependent manner.161* However, some classes may not originate from a file; they may originate162* from other sources, such as the network, or they could be constructed by an163* application. The method {@link #defineClass(String, byte[], int, int)164* defineClass} converts an array of bytes into an instance of class165* {@code Class}. Instances of this newly defined class can be created using166* {@link Class#newInstance Class.newInstance}.167*168* <p> The methods and constructors of objects created by a class loader may169* reference other classes. To determine the class(es) referred to, the Java170* virtual machine invokes the {@link #loadClass loadClass} method of171* the class loader that originally created the class.172*173* <p> For example, an application could create a network class loader to174* download class files from a server. Sample code might look like:175*176* <blockquote><pre>177* ClassLoader loader = new NetworkClassLoader(host, port);178* Object main = loader.loadClass("Main", true).newInstance();179* . . .180* </pre></blockquote>181*182* <p> The network class loader subclass must define the methods {@link183* #findClass findClass} and {@code loadClassData} to load a class184* from the network. Once it has downloaded the bytes that make up the class,185* it should use the method {@link #defineClass defineClass} to186* create a class instance. A sample implementation is:187*188* <blockquote><pre>189* class NetworkClassLoader extends ClassLoader {190* String host;191* int port;192*193* public Class findClass(String name) {194* byte[] b = loadClassData(name);195* return defineClass(name, b, 0, b.length);196* }197*198* private byte[] loadClassData(String name) {199* // load the class data from the connection200* . . .201* }202* }203* </pre></blockquote>204*205* <h3> <a id="binary-name">Binary names</a> </h3>206*207* <p> Any class name provided as a {@code String} parameter to methods in208* {@code ClassLoader} must be a binary name as defined by209* <cite>The Java Language Specification</cite>.210*211* <p> Examples of valid class names include:212* <blockquote><pre>213* "java.lang.String"214* "javax.swing.JSpinner$DefaultEditor"215* "java.security.KeyStore$Builder$FileBuilder$1"216* "java.net.URLClassLoader$3$1"217* </pre></blockquote>218*219* <p> Any package name provided as a {@code String} parameter to methods in220* {@code ClassLoader} must be either the empty string (denoting an unnamed package)221* or a fully qualified name as defined by222* <cite>The Java Language Specification</cite>.223*224* @jls 6.7 Fully Qualified Names225* @jls 13.1 The Form of a Binary226* @see #resolveClass(Class)227* @since 1.0228* @revised 9229*/230public abstract class ClassLoader {231232private static native void registerNatives();233static {234registerNatives();235}236237// The parent class loader for delegation238// Note: VM hardcoded the offset of this field, thus all new fields239// must be added *after* it.240private final ClassLoader parent;241242// class loader name243private final String name;244245// the unnamed module for this ClassLoader246private final Module unnamedModule;247248// a string for exception message printing249private final String nameAndId;250251/**252* Encapsulates the set of parallel capable loader types.253*/254private static class ParallelLoaders {255private ParallelLoaders() {}256257// the set of parallel capable loader types258private static final Set<Class<? extends ClassLoader>> loaderTypes =259Collections.newSetFromMap(new WeakHashMap<>());260static {261synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }262}263264/**265* Registers the given class loader type as parallel capable.266* Returns {@code true} is successfully registered; {@code false} if267* loader's super class is not registered.268*/269static boolean register(Class<? extends ClassLoader> c) {270synchronized (loaderTypes) {271if (loaderTypes.contains(c.getSuperclass())) {272// register the class loader as parallel capable273// if and only if all of its super classes are.274// Note: given current classloading sequence, if275// the immediate super class is parallel capable,276// all the super classes higher up must be too.277loaderTypes.add(c);278return true;279} else {280return false;281}282}283}284285/**286* Returns {@code true} if the given class loader type is287* registered as parallel capable.288*/289static boolean isRegistered(Class<? extends ClassLoader> c) {290synchronized (loaderTypes) {291return loaderTypes.contains(c);292}293}294}295296// Maps class name to the corresponding lock object when the current297// class loader is parallel capable.298// Note: VM also uses this field to decide if the current class loader299// is parallel capable and the appropriate lock object for class loading.300private final ConcurrentHashMap<String, Object> parallelLockMap;301302// Maps packages to certs303private final ConcurrentHashMap<String, Certificate[]> package2certs;304305// Shared among all packages with unsigned classes306private static final Certificate[] nocerts = new Certificate[0];307308// The classes loaded by this class loader. The only purpose of this table309// is to keep the classes from being GC'ed until the loader is GC'ed.310private final ArrayList<Class<?>> classes = new ArrayList<>();311312// The "default" domain. Set as the default ProtectionDomain on newly313// created classes.314private final ProtectionDomain defaultDomain =315new ProtectionDomain(new CodeSource(null, (Certificate[]) null),316null, this, null);317318// Invoked by the VM to record every loaded class with this loader.319void addClass(Class<?> c) {320synchronized (classes) {321classes.add(c);322}323}324325// The packages defined in this class loader. Each package name is326// mapped to its corresponding NamedPackage object.327//328// The value is a Package object if ClassLoader::definePackage,329// Class::getPackage, ClassLoader::getDefinePackage(s) or330// Package::getPackage(s) method is called to define it.331// Otherwise, the value is a NamedPackage object.332private final ConcurrentHashMap<String, NamedPackage> packages333= new ConcurrentHashMap<>();334335/*336* Returns a named package for the given module.337*/338private NamedPackage getNamedPackage(String pn, Module m) {339NamedPackage p = packages.get(pn);340if (p == null) {341p = new NamedPackage(pn, m);342343NamedPackage value = packages.putIfAbsent(pn, p);344if (value != null) {345// Package object already be defined for the named package346p = value;347// if definePackage is called by this class loader to define348// a package in a named module, this will return Package349// object of the same name. Package object may contain350// unexpected information but it does not impact the runtime.351// this assertion may be helpful for troubleshooting352assert value.module() == m;353}354}355return p;356}357358private static Void checkCreateClassLoader() {359return checkCreateClassLoader(null);360}361362private static Void checkCreateClassLoader(String name) {363if (name != null && name.isEmpty()) {364throw new IllegalArgumentException("name must be non-empty or null");365}366367@SuppressWarnings("removal")368SecurityManager security = System.getSecurityManager();369if (security != null) {370security.checkCreateClassLoader();371}372return null;373}374375private ClassLoader(Void unused, String name, ClassLoader parent) {376this.name = name;377this.parent = parent;378this.unnamedModule = new Module(this);379if (ParallelLoaders.isRegistered(this.getClass())) {380parallelLockMap = new ConcurrentHashMap<>();381assertionLock = new Object();382} else {383// no finer-grained lock; lock on the classloader instance384parallelLockMap = null;385assertionLock = this;386}387this.package2certs = new ConcurrentHashMap<>();388this.nameAndId = nameAndId(this);389}390391/**392* If the defining loader has a name explicitly set then393* '<loader-name>' @<id>394* If the defining loader has no name then395* <qualified-class-name> @<id>396* If it's built-in loader then omit `@<id>` as there is only one instance.397*/398private static String nameAndId(ClassLoader ld) {399String nid = ld.getName() != null ? "\'" + ld.getName() + "\'"400: ld.getClass().getName();401if (!(ld instanceof BuiltinClassLoader)) {402String id = Integer.toHexString(System.identityHashCode(ld));403nid = nid + " @" + id;404}405return nid;406}407408/**409* Creates a new class loader of the specified name and using the410* specified parent class loader for delegation.411*412* @apiNote If the parent is specified as {@code null} (for the413* bootstrap class loader) then there is no guarantee that all platform414* classes are visible.415*416* @param name class loader name; or {@code null} if not named417* @param parent the parent class loader418*419* @throws IllegalArgumentException if the given name is empty.420*421* @throws SecurityException422* If a security manager exists and its423* {@link SecurityManager#checkCreateClassLoader()}424* method doesn't allow creation of a new class loader.425*426* @since 9427*/428protected ClassLoader(String name, ClassLoader parent) {429this(checkCreateClassLoader(name), name, parent);430}431432/**433* Creates a new class loader using the specified parent class loader for434* delegation.435*436* <p> If there is a security manager, its {@link437* SecurityManager#checkCreateClassLoader() checkCreateClassLoader} method438* is invoked. This may result in a security exception. </p>439*440* @apiNote If the parent is specified as {@code null} (for the441* bootstrap class loader) then there is no guarantee that all platform442* classes are visible.443*444* @param parent445* The parent class loader446*447* @throws SecurityException448* If a security manager exists and its449* {@code checkCreateClassLoader} method doesn't allow creation450* of a new class loader.451*452* @since 1.2453*/454protected ClassLoader(ClassLoader parent) {455this(checkCreateClassLoader(), null, parent);456}457458/**459* Creates a new class loader using the {@code ClassLoader} returned by460* the method {@link #getSystemClassLoader()461* getSystemClassLoader()} as the parent class loader.462*463* <p> If there is a security manager, its {@link464* SecurityManager#checkCreateClassLoader()465* checkCreateClassLoader} method is invoked. This may result in466* a security exception. </p>467*468* @throws SecurityException469* If a security manager exists and its470* {@code checkCreateClassLoader} method doesn't allow creation471* of a new class loader.472*/473protected ClassLoader() {474this(checkCreateClassLoader(), null, getSystemClassLoader());475}476477/**478* Returns the name of this class loader or {@code null} if479* this class loader is not named.480*481* @apiNote This method is non-final for compatibility. If this482* method is overridden, this method must return the same name483* as specified when this class loader was instantiated.484*485* @return name of this class loader; or {@code null} if486* this class loader is not named.487*488* @since 9489*/490public String getName() {491return name;492}493494// package-private used by StackTraceElement to avoid495// calling the overrideable getName method496final String name() {497return name;498}499500// -- Class --501502/**503* Loads the class with the specified <a href="#binary-name">binary name</a>.504* This method searches for classes in the same manner as the {@link505* #loadClass(String, boolean)} method. It is invoked by the Java virtual506* machine to resolve class references. Invoking this method is equivalent507* to invoking {@link #loadClass(String, boolean) loadClass(name,508* false)}.509*510* @param name511* The <a href="#binary-name">binary name</a> of the class512*513* @return The resulting {@code Class} object514*515* @throws ClassNotFoundException516* If the class was not found517*/518public Class<?> loadClass(String name) throws ClassNotFoundException {519return loadClass(name, false);520}521522/**523* Loads the class with the specified <a href="#binary-name">binary name</a>. The524* default implementation of this method searches for classes in the525* following order:526*527* <ol>528*529* <li><p> Invoke {@link #findLoadedClass(String)} to check if the class530* has already been loaded. </p></li>531*532* <li><p> Invoke the {@link #loadClass(String) loadClass} method533* on the parent class loader. If the parent is {@code null} the class534* loader built into the virtual machine is used, instead. </p></li>535*536* <li><p> Invoke the {@link #findClass(String)} method to find the537* class. </p></li>538*539* </ol>540*541* <p> If the class was found using the above steps, and the542* {@code resolve} flag is true, this method will then invoke the {@link543* #resolveClass(Class)} method on the resulting {@code Class} object.544*545* <p> Subclasses of {@code ClassLoader} are encouraged to override {@link546* #findClass(String)}, rather than this method. </p>547*548* <p> Unless overridden, this method synchronizes on the result of549* {@link #getClassLoadingLock getClassLoadingLock} method550* during the entire class loading process.551*552* @param name553* The <a href="#binary-name">binary name</a> of the class554*555* @param resolve556* If {@code true} then resolve the class557*558* @return The resulting {@code Class} object559*560* @throws ClassNotFoundException561* If the class could not be found562*/563protected Class<?> loadClass(String name, boolean resolve)564throws ClassNotFoundException565{566synchronized (getClassLoadingLock(name)) {567// First, check if the class has already been loaded568Class<?> c = findLoadedClass(name);569if (c == null) {570long t0 = System.nanoTime();571try {572if (parent != null) {573c = parent.loadClass(name, false);574} else {575c = findBootstrapClassOrNull(name);576}577} catch (ClassNotFoundException e) {578// ClassNotFoundException thrown if class not found579// from the non-null parent class loader580}581582if (c == null) {583// If still not found, then invoke findClass in order584// to find the class.585long t1 = System.nanoTime();586c = findClass(name);587588// this is the defining class loader; record the stats589PerfCounter.getParentDelegationTime().addTime(t1 - t0);590PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);591PerfCounter.getFindClasses().increment();592}593}594if (resolve) {595resolveClass(c);596}597return c;598}599}600601/**602* Loads the class with the specified <a href="#binary-name">binary name</a>603* in a module defined to this class loader. This method returns {@code null}604* if the class could not be found.605*606* @apiNote This method does not delegate to the parent class loader.607*608* @implSpec The default implementation of this method searches for classes609* in the following order:610*611* <ol>612* <li>Invoke {@link #findLoadedClass(String)} to check if the class613* has already been loaded.</li>614* <li>Invoke the {@link #findClass(String, String)} method to find the615* class in the given module.</li>616* </ol>617*618* @param module619* The module620* @param name621* The <a href="#binary-name">binary name</a> of the class622*623* @return The resulting {@code Class} object in a module defined by624* this class loader, or {@code null} if the class could not be found.625*/626final Class<?> loadClass(Module module, String name) {627synchronized (getClassLoadingLock(name)) {628// First, check if the class has already been loaded629Class<?> c = findLoadedClass(name);630if (c == null) {631c = findClass(module.getName(), name);632}633if (c != null && c.getModule() == module) {634return c;635} else {636return null;637}638}639}640641/**642* Returns the lock object for class loading operations.643* For backward compatibility, the default implementation of this method644* behaves as follows. If this ClassLoader object is registered as645* parallel capable, the method returns a dedicated object associated646* with the specified class name. Otherwise, the method returns this647* ClassLoader object.648*649* @param className650* The name of the to-be-loaded class651*652* @return the lock for class loading operations653*654* @throws NullPointerException655* If registered as parallel capable and {@code className} is null656*657* @see #loadClass(String, boolean)658*659* @since 1.7660*/661protected Object getClassLoadingLock(String className) {662Object lock = this;663if (parallelLockMap != null) {664Object newLock = new Object();665lock = parallelLockMap.putIfAbsent(className, newLock);666if (lock == null) {667lock = newLock;668}669}670return lock;671}672673// Invoked by the VM after loading class with this loader.674@SuppressWarnings("removal")675private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {676final SecurityManager sm = System.getSecurityManager();677if (sm != null) {678if (ReflectUtil.isNonPublicProxyClass(cls)) {679for (Class<?> intf: cls.getInterfaces()) {680checkPackageAccess(intf, pd);681}682return;683}684685final String packageName = cls.getPackageName();686if (!packageName.isEmpty()) {687AccessController.doPrivileged(new PrivilegedAction<>() {688public Void run() {689sm.checkPackageAccess(packageName);690return null;691}692}, new AccessControlContext(new ProtectionDomain[] {pd}));693}694}695}696697/**698* Finds the class with the specified <a href="#binary-name">binary name</a>.699* This method should be overridden by class loader implementations that700* follow the delegation model for loading classes, and will be invoked by701* the {@link #loadClass loadClass} method after checking the702* parent class loader for the requested class.703*704* @implSpec The default implementation throws {@code ClassNotFoundException}.705*706* @param name707* The <a href="#binary-name">binary name</a> of the class708*709* @return The resulting {@code Class} object710*711* @throws ClassNotFoundException712* If the class could not be found713*714* @since 1.2715*/716protected Class<?> findClass(String name) throws ClassNotFoundException {717throw new ClassNotFoundException(name);718}719720/**721* Finds the class with the given <a href="#binary-name">binary name</a>722* in a module defined to this class loader.723* Class loader implementations that support loading from modules724* should override this method.725*726* @apiNote This method returns {@code null} rather than throwing727* {@code ClassNotFoundException} if the class could not be found.728*729* @implSpec The default implementation attempts to find the class by730* invoking {@link #findClass(String)} when the {@code moduleName} is731* {@code null}. It otherwise returns {@code null}.732*733* @param moduleName734* The module name; or {@code null} to find the class in the735* {@linkplain #getUnnamedModule() unnamed module} for this736* class loader737* @param name738* The <a href="#binary-name">binary name</a> of the class739*740* @return The resulting {@code Class} object, or {@code null}741* if the class could not be found.742*743* @since 9744*/745protected Class<?> findClass(String moduleName, String name) {746if (moduleName == null) {747try {748return findClass(name);749} catch (ClassNotFoundException ignore) { }750}751return null;752}753754755/**756* Converts an array of bytes into an instance of class {@code Class}.757* Before the {@code Class} can be used it must be resolved. This method758* is deprecated in favor of the version that takes a <a759* href="#binary-name">binary name</a> as its first argument, and is more secure.760*761* @param b762* The bytes that make up the class data. The bytes in positions763* {@code off} through {@code off+len-1} should have the format764* of a valid class file as defined by765* <cite>The Java Virtual Machine Specification</cite>.766*767* @param off768* The start offset in {@code b} of the class data769*770* @param len771* The length of the class data772*773* @return The {@code Class} object that was created from the specified774* class data775*776* @throws ClassFormatError777* If the data did not contain a valid class778*779* @throws IndexOutOfBoundsException780* If either {@code off} or {@code len} is negative, or if781* {@code off+len} is greater than {@code b.length}.782*783* @throws SecurityException784* If an attempt is made to add this class to a package that785* contains classes that were signed by a different set of786* certificates than this class, or if an attempt is made787* to define a class in a package with a fully-qualified name788* that starts with "{@code java.}".789*790* @see #loadClass(String, boolean)791* @see #resolveClass(Class)792*793* @deprecated Replaced by {@link #defineClass(String, byte[], int, int)794* defineClass(String, byte[], int, int)}795*/796@Deprecated(since="1.1")797protected final Class<?> defineClass(byte[] b, int off, int len)798throws ClassFormatError799{800return defineClass(null, b, off, len, null);801}802803/**804* Converts an array of bytes into an instance of class {@code Class}.805* Before the {@code Class} can be used it must be resolved.806*807* <p> This method assigns a default {@link java.security.ProtectionDomain808* ProtectionDomain} to the newly defined class. The809* {@code ProtectionDomain} is effectively granted the same set of810* permissions returned when {@link811* java.security.Policy#getPermissions(java.security.CodeSource)812* Policy.getPolicy().getPermissions(new CodeSource(null, null))}813* is invoked. The default protection domain is created on the first invocation814* of {@link #defineClass(String, byte[], int, int) defineClass},815* and re-used on subsequent invocations.816*817* <p> To assign a specific {@code ProtectionDomain} to the class, use818* the {@link #defineClass(String, byte[], int, int,819* java.security.ProtectionDomain) defineClass} method that takes a820* {@code ProtectionDomain} as one of its arguments. </p>821*822* <p>823* This method defines a package in this class loader corresponding to the824* package of the {@code Class} (if such a package has not already been defined825* in this class loader). The name of the defined package is derived from826* the <a href="#binary-name">binary name</a> of the class specified by827* the byte array {@code b}.828* Other properties of the defined package are as specified by {@link Package}.829*830* @param name831* The expected <a href="#binary-name">binary name</a> of the class, or832* {@code null} if not known833*834* @param b835* The bytes that make up the class data. The bytes in positions836* {@code off} through {@code off+len-1} should have the format837* of a valid class file as defined by838* <cite>The Java Virtual Machine Specification</cite>.839*840* @param off841* The start offset in {@code b} of the class data842*843* @param len844* The length of the class data845*846* @return The {@code Class} object that was created from the specified847* class data.848*849* @throws ClassFormatError850* If the data did not contain a valid class851*852* @throws IndexOutOfBoundsException853* If either {@code off} or {@code len} is negative, or if854* {@code off+len} is greater than {@code b.length}.855*856* @throws SecurityException857* If an attempt is made to add this class to a package that858* contains classes that were signed by a different set of859* certificates than this class (which is unsigned), or if860* {@code name} begins with "{@code java.}".861*862* @see #loadClass(String, boolean)863* @see #resolveClass(Class)864* @see java.security.CodeSource865* @see java.security.SecureClassLoader866*867* @since 1.1868* @revised 9869*/870protected final Class<?> defineClass(String name, byte[] b, int off, int len)871throws ClassFormatError872{873return defineClass(name, b, off, len, null);874}875876/* Determine protection domain, and check that:877- not define java.* class,878- signer of this class matches signers for the rest of the classes in879package.880*/881private ProtectionDomain preDefineClass(String name,882ProtectionDomain pd)883{884if (!checkName(name))885throw new NoClassDefFoundError("IllegalName: " + name);886887// Note: Checking logic in java.lang.invoke.MemberName.checkForTypeAlias888// relies on the fact that spoofing is impossible if a class has a name889// of the form "java.*"890if ((name != null) && name.startsWith("java.")891&& this != getBuiltinPlatformClassLoader()) {892throw new SecurityException893("Prohibited package name: " +894name.substring(0, name.lastIndexOf('.')));895}896if (pd == null) {897pd = defaultDomain;898}899900if (name != null) {901checkCerts(name, pd.getCodeSource());902}903904return pd;905}906907private String defineClassSourceLocation(ProtectionDomain pd) {908CodeSource cs = pd.getCodeSource();909String source = null;910if (cs != null && cs.getLocation() != null) {911source = cs.getLocation().toString();912}913return source;914}915916private void postDefineClass(Class<?> c, ProtectionDomain pd) {917// define a named package, if not present918getNamedPackage(c.getPackageName(), c.getModule());919920if (pd.getCodeSource() != null) {921Certificate certs[] = pd.getCodeSource().getCertificates();922if (certs != null)923setSigners(c, certs);924}925}926927/**928* Converts an array of bytes into an instance of class {@code Class},929* with a given {@code ProtectionDomain}.930*931* <p> If the given {@code ProtectionDomain} is {@code null},932* then a default protection domain will be assigned to the class as specified933* in the documentation for {@link #defineClass(String, byte[], int, int)}.934* Before the class can be used it must be resolved.935*936* <p> The first class defined in a package determines the exact set of937* certificates that all subsequent classes defined in that package must938* contain. The set of certificates for a class is obtained from the939* {@link java.security.CodeSource CodeSource} within the940* {@code ProtectionDomain} of the class. Any classes added to that941* package must contain the same set of certificates or a942* {@code SecurityException} will be thrown. Note that if943* {@code name} is {@code null}, this check is not performed.944* You should always pass in the <a href="#binary-name">binary name</a> of the945* class you are defining as well as the bytes. This ensures that the946* class you are defining is indeed the class you think it is.947*948* <p> If the specified {@code name} begins with "{@code java.}", it can949* only be defined by the {@linkplain #getPlatformClassLoader()950* platform class loader} or its ancestors; otherwise {@code SecurityException}951* will be thrown. If {@code name} is not {@code null}, it must be equal to952* the <a href="#binary-name">binary name</a> of the class953* specified by the byte array {@code b}, otherwise a {@link954* NoClassDefFoundError NoClassDefFoundError} will be thrown.955*956* <p> This method defines a package in this class loader corresponding to the957* package of the {@code Class} (if such a package has not already been defined958* in this class loader). The name of the defined package is derived from959* the <a href="#binary-name">binary name</a> of the class specified by960* the byte array {@code b}.961* Other properties of the defined package are as specified by {@link Package}.962*963* @param name964* The expected <a href="#binary-name">binary name</a> of the class, or965* {@code null} if not known966*967* @param b968* The bytes that make up the class data. The bytes in positions969* {@code off} through {@code off+len-1} should have the format970* of a valid class file as defined by971* <cite>The Java Virtual Machine Specification</cite>.972*973* @param off974* The start offset in {@code b} of the class data975*976* @param len977* The length of the class data978*979* @param protectionDomain980* The {@code ProtectionDomain} of the class981*982* @return The {@code Class} object created from the data,983* and {@code ProtectionDomain}.984*985* @throws ClassFormatError986* If the data did not contain a valid class987*988* @throws NoClassDefFoundError989* If {@code name} is not {@code null} and not equal to the990* <a href="#binary-name">binary name</a> of the class specified by {@code b}991*992* @throws IndexOutOfBoundsException993* If either {@code off} or {@code len} is negative, or if994* {@code off+len} is greater than {@code b.length}.995*996* @throws SecurityException997* If an attempt is made to add this class to a package that998* contains classes that were signed by a different set of999* certificates than this class, or if {@code name} begins with1000* "{@code java.}" and this class loader is not the platform1001* class loader or its ancestor.1002*1003* @revised 91004*/1005protected final Class<?> defineClass(String name, byte[] b, int off, int len,1006ProtectionDomain protectionDomain)1007throws ClassFormatError1008{1009protectionDomain = preDefineClass(name, protectionDomain);1010String source = defineClassSourceLocation(protectionDomain);1011Class<?> c = defineClass1(this, name, b, off, len, protectionDomain, source);1012postDefineClass(c, protectionDomain);1013return c;1014}10151016/**1017* Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance1018* of class {@code Class}, with the given {@code ProtectionDomain}.1019* If the given {@code ProtectionDomain} is {@code null}, then a default1020* protection domain will be assigned to the class as1021* specified in the documentation for {@link #defineClass(String, byte[],1022* int, int)}. Before the class can be used it must be resolved.1023*1024* <p>The rules about the first class defined in a package determining the1025* set of certificates for the package, the restrictions on class names,1026* and the defined package of the class1027* are identical to those specified in the documentation for {@link1028* #defineClass(String, byte[], int, int, ProtectionDomain)}.1029*1030* <p> An invocation of this method of the form1031* <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,}1032* <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same1033* result as the statements1034*1035*<p> <code>1036* ...<br>1037* byte[] temp = new byte[bBuffer.{@link1038* java.nio.ByteBuffer#remaining remaining}()];<br>1039* bBuffer.{@link java.nio.ByteBuffer#get(byte[])1040* get}(temp);<br>1041* return {@link #defineClass(String, byte[], int, int, ProtectionDomain)1042* cl.defineClass}(name, temp, 0,1043* temp.length, pd);<br>1044* </code></p>1045*1046* @param name1047* The expected <a href="#binary-name">binary name</a>. of the class, or1048* {@code null} if not known1049*1050* @param b1051* The bytes that make up the class data. The bytes from positions1052* {@code b.position()} through {@code b.position() + b.limit() -11053* } should have the format of a valid class file as defined by1054* <cite>The Java Virtual Machine Specification</cite>.1055*1056* @param protectionDomain1057* The {@code ProtectionDomain} of the class, or {@code null}.1058*1059* @return The {@code Class} object created from the data,1060* and {@code ProtectionDomain}.1061*1062* @throws ClassFormatError1063* If the data did not contain a valid class.1064*1065* @throws NoClassDefFoundError1066* If {@code name} is not {@code null} and not equal to the1067* <a href="#binary-name">binary name</a> of the class specified by {@code b}1068*1069* @throws SecurityException1070* If an attempt is made to add this class to a package that1071* contains classes that were signed by a different set of1072* certificates than this class, or if {@code name} begins with1073* "{@code java.}".1074*1075* @see #defineClass(String, byte[], int, int, ProtectionDomain)1076*1077* @since 1.51078* @revised 91079*/1080protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,1081ProtectionDomain protectionDomain)1082throws ClassFormatError1083{1084int len = b.remaining();10851086// Use byte[] if not a direct ByteBuffer:1087if (!b.isDirect()) {1088if (b.hasArray()) {1089return defineClass(name, b.array(),1090b.position() + b.arrayOffset(), len,1091protectionDomain);1092} else {1093// no array, or read-only array1094byte[] tb = new byte[len];1095b.get(tb); // get bytes out of byte buffer.1096return defineClass(name, tb, 0, len, protectionDomain);1097}1098}10991100protectionDomain = preDefineClass(name, protectionDomain);1101String source = defineClassSourceLocation(protectionDomain);1102Class<?> c = defineClass2(this, name, b, b.position(), len, protectionDomain, source);1103postDefineClass(c, protectionDomain);1104return c;1105}11061107static native Class<?> defineClass1(ClassLoader loader, String name, byte[] b, int off, int len,1108ProtectionDomain pd, String source);11091110static native Class<?> defineClass2(ClassLoader loader, String name, java.nio.ByteBuffer b,1111int off, int len, ProtectionDomain pd,1112String source);11131114/**1115* Defines a class of the given flags via Lookup.defineClass.1116*1117* @param loader the defining loader1118* @param lookup nest host of the Class to be defined1119* @param name the binary name or {@code null} if not findable1120* @param b class bytes1121* @param off the start offset in {@code b} of the class bytes1122* @param len the length of the class bytes1123* @param pd protection domain1124* @param initialize initialize the class1125* @param flags flags1126* @param classData class data1127*/1128static native Class<?> defineClass0(ClassLoader loader,1129Class<?> lookup,1130String name,1131byte[] b, int off, int len,1132ProtectionDomain pd,1133boolean initialize,1134int flags,1135Object classData);11361137// true if the name is null or has the potential to be a valid binary name1138private static boolean checkName(String name) {1139if ((name == null) || (name.isEmpty()))1140return true;1141if ((name.indexOf('/') != -1) || (name.charAt(0) == '['))1142return false;1143return true;1144}11451146private void checkCerts(String name, CodeSource cs) {1147int i = name.lastIndexOf('.');1148String pname = (i == -1) ? "" : name.substring(0, i);11491150Certificate[] certs = null;1151if (cs != null) {1152certs = cs.getCertificates();1153}1154certs = certs == null ? nocerts : certs;1155Certificate[] pcerts = package2certs.putIfAbsent(pname, certs);1156if (pcerts != null && !compareCerts(pcerts, certs)) {1157throw new SecurityException("class \"" + name1158+ "\"'s signer information does not match signer information"1159+ " of other classes in the same package");1160}1161}11621163/**1164* check to make sure the certs for the new class (certs) are the same as1165* the certs for the first class inserted in the package (pcerts)1166*/1167private boolean compareCerts(Certificate[] pcerts, Certificate[] certs) {1168// empty array fast-path1169if (certs.length == 0)1170return pcerts.length == 0;11711172// the length must be the same at this point1173if (certs.length != pcerts.length)1174return false;11751176// go through and make sure all the certs in one array1177// are in the other and vice-versa.1178boolean match;1179for (Certificate cert : certs) {1180match = false;1181for (Certificate pcert : pcerts) {1182if (cert.equals(pcert)) {1183match = true;1184break;1185}1186}1187if (!match) return false;1188}11891190// now do the same for pcerts1191for (Certificate pcert : pcerts) {1192match = false;1193for (Certificate cert : certs) {1194if (pcert.equals(cert)) {1195match = true;1196break;1197}1198}1199if (!match) return false;1200}12011202return true;1203}12041205/**1206* Links the specified class. This (misleadingly named) method may be1207* used by a class loader to link a class. If the class {@code c} has1208* already been linked, then this method simply returns. Otherwise, the1209* class is linked as described in the "Execution" chapter of1210* <cite>The Java Language Specification</cite>.1211*1212* @param c1213* The class to link1214*1215* @throws NullPointerException1216* If {@code c} is {@code null}.1217*1218* @see #defineClass(String, byte[], int, int)1219*/1220protected final void resolveClass(Class<?> c) {1221if (c == null) {1222throw new NullPointerException();1223}1224}12251226/**1227* Finds a class with the specified <a href="#binary-name">binary name</a>,1228* loading it if necessary.1229*1230* <p> This method loads the class through the system class loader (see1231* {@link #getSystemClassLoader()}). The {@code Class} object returned1232* might have more than one {@code ClassLoader} associated with it.1233* Subclasses of {@code ClassLoader} need not usually invoke this method,1234* because most class loaders need to override just {@link1235* #findClass(String)}. </p>1236*1237* @param name1238* The <a href="#binary-name">binary name</a> of the class1239*1240* @return The {@code Class} object for the specified {@code name}1241*1242* @throws ClassNotFoundException1243* If the class could not be found1244*1245* @see #ClassLoader(ClassLoader)1246* @see #getParent()1247*/1248protected final Class<?> findSystemClass(String name)1249throws ClassNotFoundException1250{1251return getSystemClassLoader().loadClass(name);1252}12531254/**1255* Returns a class loaded by the bootstrap class loader;1256* or return null if not found.1257*/1258static Class<?> findBootstrapClassOrNull(String name) {1259if (!checkName(name)) return null;12601261return findBootstrapClass(name);1262}12631264// return null if not found1265private static native Class<?> findBootstrapClass(String name);12661267/**1268* Returns the class with the given <a href="#binary-name">binary name</a> if this1269* loader has been recorded by the Java virtual machine as an initiating1270* loader of a class with that <a href="#binary-name">binary name</a>. Otherwise1271* {@code null} is returned.1272*1273* @param name1274* The <a href="#binary-name">binary name</a> of the class1275*1276* @return The {@code Class} object, or {@code null} if the class has1277* not been loaded1278*1279* @since 1.11280*/1281protected final Class<?> findLoadedClass(String name) {1282if (!checkName(name))1283return null;1284return findLoadedClass0(name);1285}12861287private final native Class<?> findLoadedClass0(String name);12881289/**1290* Sets the signers of a class. This should be invoked after defining a1291* class.1292*1293* @param c1294* The {@code Class} object1295*1296* @param signers1297* The signers for the class1298*1299* @since 1.11300*/1301protected final void setSigners(Class<?> c, Object[] signers) {1302c.setSigners(signers);1303}130413051306// -- Resources --13071308/**1309* Returns a URL to a resource in a module defined to this class loader.1310* Class loader implementations that support loading from modules1311* should override this method.1312*1313* @apiNote This method is the basis for the {@link1314* Class#getResource Class.getResource}, {@link Class#getResourceAsStream1315* Class.getResourceAsStream}, and {@link Module#getResourceAsStream1316* Module.getResourceAsStream} methods. It is not subject to the rules for1317* encapsulation specified by {@code Module.getResourceAsStream}.1318*1319* @implSpec The default implementation attempts to find the resource by1320* invoking {@link #findResource(String)} when the {@code moduleName} is1321* {@code null}. It otherwise returns {@code null}.1322*1323* @param moduleName1324* The module name; or {@code null} to find a resource in the1325* {@linkplain #getUnnamedModule() unnamed module} for this1326* class loader1327* @param name1328* The resource name1329*1330* @return A URL to the resource; {@code null} if the resource could not be1331* found, a URL could not be constructed to locate the resource,1332* access to the resource is denied by the security manager, or1333* there isn't a module of the given name defined to the class1334* loader.1335*1336* @throws IOException1337* If I/O errors occur1338*1339* @see java.lang.module.ModuleReader#find(String)1340* @since 91341*/1342protected URL findResource(String moduleName, String name) throws IOException {1343if (moduleName == null) {1344return findResource(name);1345} else {1346return null;1347}1348}13491350/**1351* Finds the resource with the given name. A resource is some data1352* (images, audio, text, etc) that can be accessed by class code in a way1353* that is independent of the location of the code.1354*1355* <p> The name of a resource is a '{@code /}'-separated path name that1356* identifies the resource. </p>1357*1358* <p> Resources in named modules are subject to the encapsulation rules1359* specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.1360* Additionally, and except for the special case where the resource has a1361* name ending with "{@code .class}", this method will only find resources in1362* packages of named modules when the package is {@link Module#isOpen(String)1363* opened} unconditionally (even if the caller of this method is in the1364* same module as the resource). </p>1365*1366* @implSpec The default implementation will first search the parent class1367* loader for the resource; if the parent is {@code null} the path of the1368* class loader built into the virtual machine is searched. If not found,1369* this method will invoke {@link #findResource(String)} to find the resource.1370*1371* @apiNote Where several modules are defined to the same class loader,1372* and where more than one module contains a resource with the given name,1373* then the ordering that modules are searched is not specified and may be1374* very unpredictable.1375* When overriding this method it is recommended that an implementation1376* ensures that any delegation is consistent with the {@link1377* #getResources(java.lang.String) getResources(String)} method.1378*1379* @param name1380* The resource name1381*1382* @return {@code URL} object for reading the resource; {@code null} if1383* the resource could not be found, a {@code URL} could not be1384* constructed to locate the resource, the resource is in a package1385* that is not opened unconditionally, or access to the resource is1386* denied by the security manager.1387*1388* @throws NullPointerException If {@code name} is {@code null}1389*1390* @since 1.11391* @revised 91392*/1393public URL getResource(String name) {1394Objects.requireNonNull(name);1395URL url;1396if (parent != null) {1397url = parent.getResource(name);1398} else {1399url = BootLoader.findResource(name);1400}1401if (url == null) {1402url = findResource(name);1403}1404return url;1405}14061407/**1408* Finds all the resources with the given name. A resource is some data1409* (images, audio, text, etc) that can be accessed by class code in a way1410* that is independent of the location of the code.1411*1412* <p> The name of a resource is a {@code /}-separated path name that1413* identifies the resource. </p>1414*1415* <p> Resources in named modules are subject to the encapsulation rules1416* specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.1417* Additionally, and except for the special case where the resource has a1418* name ending with "{@code .class}", this method will only find resources in1419* packages of named modules when the package is {@link Module#isOpen(String)1420* opened} unconditionally (even if the caller of this method is in the1421* same module as the resource). </p>1422*1423* @implSpec The default implementation will first search the parent class1424* loader for the resource; if the parent is {@code null} the path of the1425* class loader built into the virtual machine is searched. It then1426* invokes {@link #findResources(String)} to find the resources with the1427* name in this class loader. It returns an enumeration whose elements1428* are the URLs found by searching the parent class loader followed by1429* the elements found with {@code findResources}.1430*1431* @apiNote Where several modules are defined to the same class loader,1432* and where more than one module contains a resource with the given name,1433* then the ordering is not specified and may be very unpredictable.1434* When overriding this method it is recommended that an1435* implementation ensures that any delegation is consistent with the {@link1436* #getResource(java.lang.String) getResource(String)} method. This should1437* ensure that the first element returned by the Enumeration's1438* {@code nextElement} method is the same resource that the1439* {@code getResource(String)} method would return.1440*1441* @param name1442* The resource name1443*1444* @return An enumeration of {@link java.net.URL URL} objects for the1445* resource. If no resources could be found, the enumeration will1446* be empty. Resources for which a {@code URL} cannot be1447* constructed, are in a package that is not opened1448* unconditionally, or access to the resource is denied by the1449* security manager, are not returned in the enumeration.1450*1451* @throws IOException1452* If I/O errors occur1453* @throws NullPointerException If {@code name} is {@code null}1454*1455* @since 1.21456* @revised 91457*/1458public Enumeration<URL> getResources(String name) throws IOException {1459Objects.requireNonNull(name);1460@SuppressWarnings("unchecked")1461Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];1462if (parent != null) {1463tmp[0] = parent.getResources(name);1464} else {1465tmp[0] = BootLoader.findResources(name);1466}1467tmp[1] = findResources(name);14681469return new CompoundEnumeration<>(tmp);1470}14711472/**1473* Returns a stream whose elements are the URLs of all the resources with1474* the given name. A resource is some data (images, audio, text, etc) that1475* can be accessed by class code in a way that is independent of the1476* location of the code.1477*1478* <p> The name of a resource is a {@code /}-separated path name that1479* identifies the resource.1480*1481* <p> The resources will be located when the returned stream is evaluated.1482* If the evaluation results in an {@code IOException} then the I/O1483* exception is wrapped in an {@link UncheckedIOException} that is then1484* thrown.1485*1486* <p> Resources in named modules are subject to the encapsulation rules1487* specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.1488* Additionally, and except for the special case where the resource has a1489* name ending with "{@code .class}", this method will only find resources in1490* packages of named modules when the package is {@link Module#isOpen(String)1491* opened} unconditionally (even if the caller of this method is in the1492* same module as the resource). </p>1493*1494* @implSpec The default implementation invokes {@link #getResources(String)1495* getResources} to find all the resources with the given name and returns1496* a stream with the elements in the enumeration as the source.1497*1498* @apiNote When overriding this method it is recommended that an1499* implementation ensures that any delegation is consistent with the {@link1500* #getResource(java.lang.String) getResource(String)} method. This should1501* ensure that the first element returned by the stream is the same1502* resource that the {@code getResource(String)} method would return.1503*1504* @param name1505* The resource name1506*1507* @return A stream of resource {@link java.net.URL URL} objects. If no1508* resources could be found, the stream will be empty. Resources1509* for which a {@code URL} cannot be constructed, are in a package1510* that is not opened unconditionally, or access to the resource1511* is denied by the security manager, will not be in the stream.1512*1513* @throws NullPointerException If {@code name} is {@code null}1514*1515* @since 91516*/1517public Stream<URL> resources(String name) {1518Objects.requireNonNull(name);1519int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE;1520Supplier<Spliterator<URL>> si = () -> {1521try {1522return Spliterators.spliteratorUnknownSize(1523getResources(name).asIterator(), characteristics);1524} catch (IOException e) {1525throw new UncheckedIOException(e);1526}1527};1528return StreamSupport.stream(si, characteristics, false);1529}15301531/**1532* Finds the resource with the given name. Class loader implementations1533* should override this method.1534*1535* <p> For resources in named modules then the method must implement the1536* rules for encapsulation specified in the {@code Module} {@link1537* Module#getResourceAsStream getResourceAsStream} method. Additionally,1538* it must not find non-"{@code .class}" resources in packages of named1539* modules unless the package is {@link Module#isOpen(String) opened}1540* unconditionally. </p>1541*1542* @implSpec The default implementation returns {@code null}.1543*1544* @param name1545* The resource name1546*1547* @return {@code URL} object for reading the resource; {@code null} if1548* the resource could not be found, a {@code URL} could not be1549* constructed to locate the resource, the resource is in a package1550* that is not opened unconditionally, or access to the resource is1551* denied by the security manager.1552*1553* @since 1.21554* @revised 91555*/1556protected URL findResource(String name) {1557return null;1558}15591560/**1561* Returns an enumeration of {@link java.net.URL URL} objects1562* representing all the resources with the given name. Class loader1563* implementations should override this method.1564*1565* <p> For resources in named modules then the method must implement the1566* rules for encapsulation specified in the {@code Module} {@link1567* Module#getResourceAsStream getResourceAsStream} method. Additionally,1568* it must not find non-"{@code .class}" resources in packages of named1569* modules unless the package is {@link Module#isOpen(String) opened}1570* unconditionally. </p>1571*1572* @implSpec The default implementation returns an enumeration that1573* contains no elements.1574*1575* @param name1576* The resource name1577*1578* @return An enumeration of {@link java.net.URL URL} objects for1579* the resource. If no resources could be found, the enumeration1580* will be empty. Resources for which a {@code URL} cannot be1581* constructed, are in a package that is not opened unconditionally,1582* or access to the resource is denied by the security manager,1583* are not returned in the enumeration.1584*1585* @throws IOException1586* If I/O errors occur1587*1588* @since 1.21589* @revised 91590*/1591protected Enumeration<URL> findResources(String name) throws IOException {1592return Collections.emptyEnumeration();1593}15941595/**1596* Registers the caller as1597* {@linkplain #isRegisteredAsParallelCapable() parallel capable}.1598* The registration succeeds if and only if all of the following1599* conditions are met:1600* <ol>1601* <li> no instance of the caller has been created</li>1602* <li> all of the super classes (except class Object) of the caller are1603* registered as parallel capable</li>1604* </ol>1605* <p>Note that once a class loader is registered as parallel capable, there1606* is no way to change it back.</p>1607*1608* @return {@code true} if the caller is successfully registered as1609* parallel capable and {@code false} if otherwise.1610*1611* @see #isRegisteredAsParallelCapable()1612*1613* @since 1.71614*/1615@CallerSensitive1616protected static boolean registerAsParallelCapable() {1617Class<? extends ClassLoader> callerClass =1618Reflection.getCallerClass().asSubclass(ClassLoader.class);1619return ParallelLoaders.register(callerClass);1620}16211622/**1623* Returns {@code true} if this class loader is registered as1624* {@linkplain #registerAsParallelCapable parallel capable}, otherwise1625* {@code false}.1626*1627* @return {@code true} if this class loader is parallel capable,1628* otherwise {@code false}.1629*1630* @see #registerAsParallelCapable()1631*1632* @since 91633*/1634public final boolean isRegisteredAsParallelCapable() {1635return ParallelLoaders.isRegistered(this.getClass());1636}16371638/**1639* Find a resource of the specified name from the search path used to load1640* classes. This method locates the resource through the system class1641* loader (see {@link #getSystemClassLoader()}).1642*1643* <p> Resources in named modules are subject to the encapsulation rules1644* specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.1645* Additionally, and except for the special case where the resource has a1646* name ending with "{@code .class}", this method will only find resources in1647* packages of named modules when the package is {@link Module#isOpen(String)1648* opened} unconditionally. </p>1649*1650* @param name1651* The resource name1652*1653* @return A {@link java.net.URL URL} to the resource; {@code1654* null} if the resource could not be found, a URL could not be1655* constructed to locate the resource, the resource is in a package1656* that is not opened unconditionally or access to the resource is1657* denied by the security manager.1658*1659* @since 1.11660* @revised 91661*/1662public static URL getSystemResource(String name) {1663return getSystemClassLoader().getResource(name);1664}16651666/**1667* Finds all resources of the specified name from the search path used to1668* load classes. The resources thus found are returned as an1669* {@link java.util.Enumeration Enumeration} of {@link1670* java.net.URL URL} objects.1671*1672* <p> The search order is described in the documentation for {@link1673* #getSystemResource(String)}. </p>1674*1675* <p> Resources in named modules are subject to the encapsulation rules1676* specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.1677* Additionally, and except for the special case where the resource has a1678* name ending with "{@code .class}", this method will only find resources in1679* packages of named modules when the package is {@link Module#isOpen(String)1680* opened} unconditionally. </p>1681*1682* @param name1683* The resource name1684*1685* @return An enumeration of {@link java.net.URL URL} objects for1686* the resource. If no resources could be found, the enumeration1687* will be empty. Resources for which a {@code URL} cannot be1688* constructed, are in a package that is not opened unconditionally,1689* or access to the resource is denied by the security manager,1690* are not returned in the enumeration.1691*1692* @throws IOException1693* If I/O errors occur1694*1695* @since 1.21696* @revised 91697*/1698public static Enumeration<URL> getSystemResources(String name)1699throws IOException1700{1701return getSystemClassLoader().getResources(name);1702}17031704/**1705* Returns an input stream for reading the specified resource.1706*1707* <p> The search order is described in the documentation for {@link1708* #getResource(String)}. </p>1709*1710* <p> Resources in named modules are subject to the encapsulation rules1711* specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.1712* Additionally, and except for the special case where the resource has a1713* name ending with "{@code .class}", this method will only find resources in1714* packages of named modules when the package is {@link Module#isOpen(String)1715* opened} unconditionally. </p>1716*1717* @param name1718* The resource name1719*1720* @return An input stream for reading the resource; {@code null} if the1721* resource could not be found, the resource is in a package that1722* is not opened unconditionally, or access to the resource is1723* denied by the security manager.1724*1725* @throws NullPointerException If {@code name} is {@code null}1726*1727* @since 1.11728* @revised 91729*/1730public InputStream getResourceAsStream(String name) {1731Objects.requireNonNull(name);1732URL url = getResource(name);1733try {1734return url != null ? url.openStream() : null;1735} catch (IOException e) {1736return null;1737}1738}17391740/**1741* Open for reading, a resource of the specified name from the search path1742* used to load classes. This method locates the resource through the1743* system class loader (see {@link #getSystemClassLoader()}).1744*1745* <p> Resources in named modules are subject to the encapsulation rules1746* specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.1747* Additionally, and except for the special case where the resource has a1748* name ending with "{@code .class}", this method will only find resources in1749* packages of named modules when the package is {@link Module#isOpen(String)1750* opened} unconditionally. </p>1751*1752* @param name1753* The resource name1754*1755* @return An input stream for reading the resource; {@code null} if the1756* resource could not be found, the resource is in a package that1757* is not opened unconditionally, or access to the resource is1758* denied by the security manager.1759*1760* @since 1.11761* @revised 91762*/1763public static InputStream getSystemResourceAsStream(String name) {1764URL url = getSystemResource(name);1765try {1766return url != null ? url.openStream() : null;1767} catch (IOException e) {1768return null;1769}1770}177117721773// -- Hierarchy --17741775/**1776* Returns the parent class loader for delegation. Some implementations may1777* use {@code null} to represent the bootstrap class loader. This method1778* will return {@code null} in such implementations if this class loader's1779* parent is the bootstrap class loader.1780*1781* @return The parent {@code ClassLoader}1782*1783* @throws SecurityException1784* If a security manager is present, and the caller's class loader1785* is not {@code null} and is not an ancestor of this class loader,1786* and the caller does not have the1787* {@link RuntimePermission}{@code ("getClassLoader")}1788*1789* @since 1.21790*/1791@CallerSensitive1792public final ClassLoader getParent() {1793if (parent == null)1794return null;1795@SuppressWarnings("removal")1796SecurityManager sm = System.getSecurityManager();1797if (sm != null) {1798// Check access to the parent class loader1799// If the caller's class loader is same as this class loader,1800// permission check is performed.1801checkClassLoaderPermission(parent, Reflection.getCallerClass());1802}1803return parent;1804}18051806/**1807* Returns the unnamed {@code Module} for this class loader.1808*1809* @return The unnamed Module for this class loader1810*1811* @see Module#isNamed()1812* @since 91813*/1814public final Module getUnnamedModule() {1815return unnamedModule;1816}18171818/**1819* Returns the platform class loader. All1820* <a href="#builtinLoaders">platform classes</a> are visible to1821* the platform class loader.1822*1823* @implNote The name of the builtin platform class loader is1824* {@code "platform"}.1825*1826* @return The platform {@code ClassLoader}.1827*1828* @throws SecurityException1829* If a security manager is present, and the caller's class loader is1830* not {@code null}, and the caller's class loader is not the same1831* as or an ancestor of the platform class loader,1832* and the caller does not have the1833* {@link RuntimePermission}{@code ("getClassLoader")}1834*1835* @since 91836*/1837@CallerSensitive1838public static ClassLoader getPlatformClassLoader() {1839@SuppressWarnings("removal")1840SecurityManager sm = System.getSecurityManager();1841ClassLoader loader = getBuiltinPlatformClassLoader();1842if (sm != null) {1843checkClassLoaderPermission(loader, Reflection.getCallerClass());1844}1845return loader;1846}18471848/**1849* Returns the system class loader. This is the default1850* delegation parent for new {@code ClassLoader} instances, and is1851* typically the class loader used to start the application.1852*1853* <p> This method is first invoked early in the runtime's startup1854* sequence, at which point it creates the system class loader. This1855* class loader will be the context class loader for the main application1856* thread (for example, the thread that invokes the {@code main} method of1857* the main class).1858*1859* <p> The default system class loader is an implementation-dependent1860* instance of this class.1861*1862* <p> If the system property "{@systemProperty java.system.class.loader}"1863* is defined when this method is first invoked then the value of that1864* property is taken to be the name of a class that will be returned as the1865* system class loader. The class is loaded using the default system class1866* loader and must define a public constructor that takes a single parameter1867* of type {@code ClassLoader} which is used as the delegation parent. An1868* instance is then created using this constructor with the default system1869* class loader as the parameter. The resulting class loader is defined1870* to be the system class loader. During construction, the class loader1871* should take great care to avoid calling {@code getSystemClassLoader()}.1872* If circular initialization of the system class loader is detected then1873* an {@code IllegalStateException} is thrown.1874*1875* @implNote The system property to override the system class loader is not1876* examined until the VM is almost fully initialized. Code that executes1877* this method during startup should take care not to cache the return1878* value until the system is fully initialized.1879*1880* <p> The name of the built-in system class loader is {@code "app"}.1881* The system property "{@code java.class.path}" is read during early1882* initialization of the VM to determine the class path.1883* An empty value of "{@code java.class.path}" property is interpreted1884* differently depending on whether the initial module (the module1885* containing the main class) is named or unnamed:1886* If named, the built-in system class loader will have no class path and1887* will search for classes and resources using the application module path;1888* otherwise, if unnamed, it will set the class path to the current1889* working directory.1890*1891* <p> JAR files on the class path may contain a {@code Class-Path} manifest1892* attribute to specify dependent JAR files to be included in the class path.1893* {@code Class-Path} entries must meet certain conditions for validity (see1894* the <a href="{@docRoot}/../specs/jar/jar.html#class-path-attribute">1895* JAR File Specification</a> for details). Invalid {@code Class-Path}1896* entries are ignored. For debugging purposes, ignored entries can be1897* printed to the console if the1898* {@systemProperty jdk.net.URLClassPath.showIgnoredClassPathEntries} system1899* property is set to {@code true}.1900*1901* @return The system {@code ClassLoader}1902*1903* @throws SecurityException1904* If a security manager is present, and the caller's class loader1905* is not {@code null} and is not the same as or an ancestor of the1906* system class loader, and the caller does not have the1907* {@link RuntimePermission}{@code ("getClassLoader")}1908*1909* @throws IllegalStateException1910* If invoked recursively during the construction of the class1911* loader specified by the "{@code java.system.class.loader}"1912* property.1913*1914* @throws Error1915* If the system property "{@code java.system.class.loader}"1916* is defined but the named class could not be loaded, the1917* provider class does not define the required constructor, or an1918* exception is thrown by that constructor when it is invoked. The1919* underlying cause of the error can be retrieved via the1920* {@link Throwable#getCause()} method.1921*1922* @revised 1.41923* @revised 91924*/1925@CallerSensitive1926public static ClassLoader getSystemClassLoader() {1927switch (VM.initLevel()) {1928case 0:1929case 1:1930case 2:1931// the system class loader is the built-in app class loader during startup1932return getBuiltinAppClassLoader();1933case 3:1934String msg = "getSystemClassLoader cannot be called during the system class loader instantiation";1935throw new IllegalStateException(msg);1936default:1937// system fully initialized1938assert VM.isBooted() && scl != null;1939@SuppressWarnings("removal")1940SecurityManager sm = System.getSecurityManager();1941if (sm != null) {1942checkClassLoaderPermission(scl, Reflection.getCallerClass());1943}1944return scl;1945}1946}19471948static ClassLoader getBuiltinPlatformClassLoader() {1949return ClassLoaders.platformClassLoader();1950}19511952static ClassLoader getBuiltinAppClassLoader() {1953return ClassLoaders.appClassLoader();1954}19551956/*1957* Initialize the system class loader that may be a custom class on the1958* application class path or application module path.1959*1960* @see java.lang.System#initPhase31961*/1962static synchronized ClassLoader initSystemClassLoader() {1963if (VM.initLevel() != 3) {1964throw new InternalError("system class loader cannot be set at initLevel " +1965VM.initLevel());1966}19671968// detect recursive initialization1969if (scl != null) {1970throw new IllegalStateException("recursive invocation");1971}19721973ClassLoader builtinLoader = getBuiltinAppClassLoader();19741975// All are privileged frames. No need to call doPrivileged.1976String cn = System.getProperty("java.system.class.loader");1977if (cn != null) {1978try {1979// custom class loader is only supported to be loaded from unnamed module1980Constructor<?> ctor = Class.forName(cn, false, builtinLoader)1981.getDeclaredConstructor(ClassLoader.class);1982scl = (ClassLoader) ctor.newInstance(builtinLoader);1983} catch (Exception e) {1984Throwable cause = e;1985if (e instanceof InvocationTargetException) {1986cause = e.getCause();1987if (cause instanceof Error) {1988throw (Error) cause;1989}1990}1991if (cause instanceof RuntimeException) {1992throw (RuntimeException) cause;1993}1994throw new Error(cause.getMessage(), cause);1995}1996} else {1997scl = builtinLoader;1998}1999return scl;2000}20012002// Returns true if the specified class loader can be found in this class2003// loader's delegation chain.2004boolean isAncestor(ClassLoader cl) {2005ClassLoader acl = this;2006do {2007acl = acl.parent;2008if (cl == acl) {2009return true;2010}2011} while (acl != null);2012return false;2013}20142015// Tests if class loader access requires "getClassLoader" permission2016// check. A class loader 'from' can access class loader 'to' if2017// class loader 'from' is same as class loader 'to' or an ancestor2018// of 'to'. The class loader in a system domain can access2019// any class loader.2020private static boolean needsClassLoaderPermissionCheck(ClassLoader from,2021ClassLoader to)2022{2023if (from == to)2024return false;20252026if (from == null)2027return false;20282029return !to.isAncestor(from);2030}20312032// Returns the class's class loader, or null if none.2033static ClassLoader getClassLoader(Class<?> caller) {2034// This can be null if the VM is requesting it2035if (caller == null) {2036return null;2037}2038// Circumvent security check since this is package-private2039return caller.getClassLoader0();2040}20412042/*2043* Checks RuntimePermission("getClassLoader") permission2044* if caller's class loader is not null and caller's class loader2045* is not the same as or an ancestor of the given cl argument.2046*/2047static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {2048@SuppressWarnings("removal")2049SecurityManager sm = System.getSecurityManager();2050if (sm != null) {2051// caller can be null if the VM is requesting it2052ClassLoader ccl = getClassLoader(caller);2053if (needsClassLoaderPermissionCheck(ccl, cl)) {2054sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);2055}2056}2057}20582059// The system class loader2060// @GuardedBy("ClassLoader.class")2061private static volatile ClassLoader scl;20622063// -- Package --20642065/**2066* Define a Package of the given Class object.2067*2068* If the given class represents an array type, a primitive type or void,2069* this method returns {@code null}.2070*2071* This method does not throw IllegalArgumentException.2072*/2073Package definePackage(Class<?> c) {2074if (c.isPrimitive() || c.isArray()) {2075return null;2076}20772078return definePackage(c.getPackageName(), c.getModule());2079}20802081/**2082* Defines a Package of the given name and module2083*2084* This method does not throw IllegalArgumentException.2085*2086* @param name package name2087* @param m module2088*/2089Package definePackage(String name, Module m) {2090if (name.isEmpty() && m.isNamed()) {2091throw new InternalError("unnamed package in " + m);2092}20932094// check if Package object is already defined2095NamedPackage pkg = packages.get(name);2096if (pkg instanceof Package)2097return (Package)pkg;20982099return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m));2100}21012102/*2103* Returns a Package object for the named package2104*/2105private Package toPackage(String name, NamedPackage p, Module m) {2106// define Package object if the named package is not yet defined2107if (p == null)2108return NamedPackage.toPackage(name, m);21092110// otherwise, replace the NamedPackage object with Package object2111if (p instanceof Package)2112return (Package)p;21132114return NamedPackage.toPackage(p.packageName(), p.module());2115}21162117/**2118* Defines a package by <a href="#binary-name">name</a> in this {@code ClassLoader}.2119* <p>2120* <a href="#binary-name">Package names</a> must be unique within a class loader and2121* cannot be redefined or changed once created.2122* <p>2123* If a class loader wishes to define a package with specific properties,2124* such as version information, then the class loader should call this2125* {@code definePackage} method before calling {@code defineClass}.2126* Otherwise, the2127* {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass}2128* method will define a package in this class loader corresponding to the package2129* of the newly defined class; the properties of this defined package are2130* specified by {@link Package}.2131*2132* @apiNote2133* A class loader that wishes to define a package for classes in a JAR2134* typically uses the specification and implementation titles, versions, and2135* vendors from the JAR's manifest. If the package is specified as2136* {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest,2137* the {@code URL} of the JAR file is typically used as the {@code sealBase}.2138* If classes of package {@code 'p'} defined by this class loader2139* are loaded from multiple JARs, the {@code Package} object may contain2140* different information depending on the first class of package {@code 'p'}2141* defined and which JAR's manifest is read first to explicitly define2142* package {@code 'p'}.2143*2144* <p> It is strongly recommended that a class loader does not call this2145* method to explicitly define packages in <em>named modules</em>; instead,2146* the package will be automatically defined when a class is {@linkplain2147* #defineClass(String, byte[], int, int, ProtectionDomain) being defined}.2148* If it is desirable to define {@code Package} explicitly, it should ensure2149* that all packages in a named module are defined with the properties2150* specified by {@link Package}. Otherwise, some {@code Package} objects2151* in a named module may be for example sealed with different seal base.2152*2153* @param name2154* The <a href="#binary-name">package name</a>2155*2156* @param specTitle2157* The specification title2158*2159* @param specVersion2160* The specification version2161*2162* @param specVendor2163* The specification vendor2164*2165* @param implTitle2166* The implementation title2167*2168* @param implVersion2169* The implementation version2170*2171* @param implVendor2172* The implementation vendor2173*2174* @param sealBase2175* If not {@code null}, then this package is sealed with2176* respect to the given code source {@link java.net.URL URL}2177* object. Otherwise, the package is not sealed.2178*2179* @return The newly defined {@code Package} object2180*2181* @throws NullPointerException2182* if {@code name} is {@code null}.2183*2184* @throws IllegalArgumentException2185* if a package of the given {@code name} is already2186* defined by this class loader2187*2188*2189* @since 1.22190* @revised 92191*2192* @jvms 5.3 Creation and Loading2193* @see <a href="{@docRoot}/../specs/jar/jar.html#package-sealing">2194* The JAR File Specification: Package Sealing</a>2195*/2196protected Package definePackage(String name, String specTitle,2197String specVersion, String specVendor,2198String implTitle, String implVersion,2199String implVendor, URL sealBase)2200{2201Objects.requireNonNull(name);22022203// definePackage is not final and may be overridden by custom class loader2204Package p = new Package(name, specTitle, specVersion, specVendor,2205implTitle, implVersion, implVendor,2206sealBase, this);22072208if (packages.putIfAbsent(name, p) != null)2209throw new IllegalArgumentException(name);22102211return p;2212}22132214/**2215* Returns a {@code Package} of the given <a href="#binary-name">name</a> that2216* has been defined by this class loader.2217*2218* @param name The <a href="#binary-name">package name</a>2219*2220* @return The {@code Package} of the given name that has been defined2221* by this class loader, or {@code null} if not found2222*2223* @throws NullPointerException2224* if {@code name} is {@code null}.2225*2226* @jvms 5.3 Creation and Loading2227*2228* @since 92229*/2230public final Package getDefinedPackage(String name) {2231Objects.requireNonNull(name, "name cannot be null");22322233NamedPackage p = packages.get(name);2234if (p == null)2235return null;22362237return definePackage(name, p.module());2238}22392240/**2241* Returns all of the {@code Package}s that have been defined by2242* this class loader. The returned array has no duplicated {@code Package}s2243* of the same name.2244*2245* @apiNote This method returns an array rather than a {@code Set} or {@code Stream}2246* for consistency with the existing {@link #getPackages} method.2247*2248* @return The array of {@code Package} objects that have been defined by2249* this class loader; or an zero length array if no package has been2250* defined by this class loader.2251*2252* @jvms 5.3 Creation and Loading2253*2254* @since 92255*/2256public final Package[] getDefinedPackages() {2257return packages().toArray(Package[]::new);2258}22592260/**2261* Finds a package by <a href="#binary-name">name</a> in this class loader and its ancestors.2262* <p>2263* If this class loader defines a {@code Package} of the given name,2264* the {@code Package} is returned. Otherwise, the ancestors of2265* this class loader are searched recursively (parent by parent)2266* for a {@code Package} of the given name.2267*2268* @apiNote The {@link #getPlatformClassLoader() platform class loader}2269* may delegate to the application class loader but the application class2270* loader is not its ancestor. When invoked on the platform class loader,2271* this method will not find packages defined to the application2272* class loader.2273*2274* @param name2275* The <a href="#binary-name">package name</a>2276*2277* @return The {@code Package} of the given name that has been defined by2278* this class loader or its ancestors, or {@code null} if not found.2279*2280* @throws NullPointerException2281* if {@code name} is {@code null}.2282*2283* @deprecated2284* If multiple class loaders delegate to each other and define classes2285* with the same package name, and one such loader relies on the lookup2286* behavior of {@code getPackage} to return a {@code Package} from2287* a parent loader, then the properties exposed by the {@code Package}2288* may not be as expected in the rest of the program.2289* For example, the {@code Package} will only expose annotations from the2290* {@code package-info.class} file defined by the parent loader, even if2291* annotations exist in a {@code package-info.class} file defined by2292* a child loader. A more robust approach is to use the2293* {@link ClassLoader#getDefinedPackage} method which returns2294* a {@code Package} for the specified class loader.2295*2296* @see ClassLoader#getDefinedPackage(String)2297*2298* @since 1.22299* @revised 92300*/2301@Deprecated(since="9")2302protected Package getPackage(String name) {2303Package pkg = getDefinedPackage(name);2304if (pkg == null) {2305if (parent != null) {2306pkg = parent.getPackage(name);2307} else {2308pkg = BootLoader.getDefinedPackage(name);2309}2310}2311return pkg;2312}23132314/**2315* Returns all of the {@code Package}s that have been defined by2316* this class loader and its ancestors. The returned array may contain2317* more than one {@code Package} object of the same package name, each2318* defined by a different class loader in the class loader hierarchy.2319*2320* @apiNote The {@link #getPlatformClassLoader() platform class loader}2321* may delegate to the application class loader. In other words,2322* packages in modules defined to the application class loader may be2323* visible to the platform class loader. On the other hand,2324* the application class loader is not its ancestor and hence2325* when invoked on the platform class loader, this method will not2326* return any packages defined to the application class loader.2327*2328* @return The array of {@code Package} objects that have been defined by2329* this class loader and its ancestors2330*2331* @see ClassLoader#getDefinedPackages()2332*2333* @since 1.22334* @revised 92335*/2336protected Package[] getPackages() {2337Stream<Package> pkgs = packages();2338ClassLoader ld = parent;2339while (ld != null) {2340pkgs = Stream.concat(ld.packages(), pkgs);2341ld = ld.parent;2342}2343return Stream.concat(BootLoader.packages(), pkgs)2344.toArray(Package[]::new);2345}2346234723482349// package-private23502351/**2352* Returns a stream of Packages defined in this class loader2353*/2354Stream<Package> packages() {2355return packages.values().stream()2356.map(p -> definePackage(p.packageName(), p.module()));2357}23582359// -- Native library access --23602361/**2362* Returns the absolute path name of a native library. The VM invokes this2363* method to locate the native libraries that belong to classes loaded with2364* this class loader. If this method returns {@code null}, the VM2365* searches the library along the path specified as the2366* "{@code java.library.path}" property.2367*2368* @param libname2369* The library name2370*2371* @return The absolute path of the native library2372*2373* @see System#loadLibrary(String)2374* @see System#mapLibraryName(String)2375*2376* @since 1.22377*/2378protected String findLibrary(String libname) {2379return null;2380}23812382private final NativeLibraries libraries = NativeLibraries.jniNativeLibraries(this);23832384// Invoked in the java.lang.Runtime class to implement load and loadLibrary.2385static NativeLibrary loadLibrary(Class<?> fromClass, File file) {2386ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();2387NativeLibraries libs = loader != null ? loader.libraries : BootLoader.getNativeLibraries();2388NativeLibrary nl = libs.loadLibrary(fromClass, file);2389if (nl != null) {2390return nl;2391}2392throw new UnsatisfiedLinkError("Can't load library: " + file);2393}2394static NativeLibrary loadLibrary(Class<?> fromClass, String name) {2395ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();2396if (loader == null) {2397NativeLibrary nl = BootLoader.getNativeLibraries().loadLibrary(fromClass, name);2398if (nl != null) {2399return nl;2400}2401throw new UnsatisfiedLinkError("no " + name +2402" in system library path: " + StaticProperty.sunBootLibraryPath());2403}24042405NativeLibraries libs = loader.libraries;2406// First load from the file returned from ClassLoader::findLibrary, if found.2407String libfilename = loader.findLibrary(name);2408if (libfilename != null) {2409File libfile = new File(libfilename);2410if (!libfile.isAbsolute()) {2411throw new UnsatisfiedLinkError(2412"ClassLoader.findLibrary failed to return an absolute path: " + libfilename);2413}2414NativeLibrary nl = libs.loadLibrary(fromClass, libfile);2415if (nl != null) {2416return nl;2417}2418throw new UnsatisfiedLinkError("Can't load " + libfilename);2419}2420// Then load from system library path and java library path2421NativeLibrary nl = libs.loadLibrary(fromClass, name);2422if (nl != null) {2423return nl;2424}24252426// Oops, it failed2427throw new UnsatisfiedLinkError("no " + name +2428" in java.library.path: " + StaticProperty.javaLibraryPath());2429}24302431/*2432* Invoked in the VM class linking code.2433*/2434static long findNative(ClassLoader loader, String entryName) {2435if (loader == null) {2436return BootLoader.getNativeLibraries().find(entryName);2437} else {2438return loader.libraries.find(entryName);2439}2440}24412442// -- Assertion management --24432444final Object assertionLock;24452446// The default toggle for assertion checking.2447// @GuardedBy("assertionLock")2448private boolean defaultAssertionStatus = false;24492450// Maps String packageName to Boolean package default assertion status Note2451// that the default package is placed under a null map key. If this field2452// is null then we are delegating assertion status queries to the VM, i.e.,2453// none of this ClassLoader's assertion status modification methods have2454// been invoked.2455// @GuardedBy("assertionLock")2456private Map<String, Boolean> packageAssertionStatus = null;24572458// Maps String fullyQualifiedClassName to Boolean assertionStatus If this2459// field is null then we are delegating assertion status queries to the VM,2460// i.e., none of this ClassLoader's assertion status modification methods2461// have been invoked.2462// @GuardedBy("assertionLock")2463Map<String, Boolean> classAssertionStatus = null;24642465/**2466* Sets the default assertion status for this class loader. This setting2467* determines whether classes loaded by this class loader and initialized2468* in the future will have assertions enabled or disabled by default.2469* This setting may be overridden on a per-package or per-class basis by2470* invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link2471* #setClassAssertionStatus(String, boolean)}.2472*2473* @param enabled2474* {@code true} if classes loaded by this class loader will2475* henceforth have assertions enabled by default, {@code false}2476* if they will have assertions disabled by default.2477*2478* @since 1.42479*/2480public void setDefaultAssertionStatus(boolean enabled) {2481synchronized (assertionLock) {2482if (classAssertionStatus == null)2483initializeJavaAssertionMaps();24842485defaultAssertionStatus = enabled;2486}2487}24882489/**2490* Sets the package default assertion status for the named package. The2491* package default assertion status determines the assertion status for2492* classes initialized in the future that belong to the named package or2493* any of its "subpackages".2494*2495* <p> A subpackage of a package named p is any package whose name begins2496* with "{@code p.}". For example, {@code javax.swing.text} is a2497* subpackage of {@code javax.swing}, and both {@code java.util} and2498* {@code java.lang.reflect} are subpackages of {@code java}.2499*2500* <p> In the event that multiple package defaults apply to a given class,2501* the package default pertaining to the most specific package takes2502* precedence over the others. For example, if {@code javax.lang} and2503* {@code javax.lang.reflect} both have package defaults associated with2504* them, the latter package default applies to classes in2505* {@code javax.lang.reflect}.2506*2507* <p> Package defaults take precedence over the class loader's default2508* assertion status, and may be overridden on a per-class basis by invoking2509* {@link #setClassAssertionStatus(String, boolean)}. </p>2510*2511* @param packageName2512* The name of the package whose package default assertion status2513* is to be set. A {@code null} value indicates the unnamed2514* package that is "current"2515* (see section {@jls 7.4.2} of2516* <cite>The Java Language Specification</cite>.)2517*2518* @param enabled2519* {@code true} if classes loaded by this classloader and2520* belonging to the named package or any of its subpackages will2521* have assertions enabled by default, {@code false} if they will2522* have assertions disabled by default.2523*2524* @since 1.42525*/2526public void setPackageAssertionStatus(String packageName,2527boolean enabled) {2528synchronized (assertionLock) {2529if (packageAssertionStatus == null)2530initializeJavaAssertionMaps();25312532packageAssertionStatus.put(packageName, enabled);2533}2534}25352536/**2537* Sets the desired assertion status for the named top-level class in this2538* class loader and any nested classes contained therein. This setting2539* takes precedence over the class loader's default assertion status, and2540* over any applicable per-package default. This method has no effect if2541* the named class has already been initialized. (Once a class is2542* initialized, its assertion status cannot change.)2543*2544* <p> If the named class is not a top-level class, this invocation will2545* have no effect on the actual assertion status of any class. </p>2546*2547* @param className2548* The fully qualified class name of the top-level class whose2549* assertion status is to be set.2550*2551* @param enabled2552* {@code true} if the named class is to have assertions2553* enabled when (and if) it is initialized, {@code false} if the2554* class is to have assertions disabled.2555*2556* @since 1.42557*/2558public void setClassAssertionStatus(String className, boolean enabled) {2559synchronized (assertionLock) {2560if (classAssertionStatus == null)2561initializeJavaAssertionMaps();25622563classAssertionStatus.put(className, enabled);2564}2565}25662567/**2568* Sets the default assertion status for this class loader to2569* {@code false} and discards any package defaults or class assertion2570* status settings associated with the class loader. This method is2571* provided so that class loaders can be made to ignore any command line or2572* persistent assertion status settings and "start with a clean slate."2573*2574* @since 1.42575*/2576public void clearAssertionStatus() {2577/*2578* Whether or not "Java assertion maps" are initialized, set2579* them to empty maps, effectively ignoring any present settings.2580*/2581synchronized (assertionLock) {2582classAssertionStatus = new HashMap<>();2583packageAssertionStatus = new HashMap<>();2584defaultAssertionStatus = false;2585}2586}25872588/**2589* Returns the assertion status that would be assigned to the specified2590* class if it were to be initialized at the time this method is invoked.2591* If the named class has had its assertion status set, the most recent2592* setting will be returned; otherwise, if any package default assertion2593* status pertains to this class, the most recent setting for the most2594* specific pertinent package default assertion status is returned;2595* otherwise, this class loader's default assertion status is returned.2596* </p>2597*2598* @param className2599* The fully qualified class name of the class whose desired2600* assertion status is being queried.2601*2602* @return The desired assertion status of the specified class.2603*2604* @see #setClassAssertionStatus(String, boolean)2605* @see #setPackageAssertionStatus(String, boolean)2606* @see #setDefaultAssertionStatus(boolean)2607*2608* @since 1.42609*/2610boolean desiredAssertionStatus(String className) {2611synchronized (assertionLock) {2612// assert classAssertionStatus != null;2613// assert packageAssertionStatus != null;26142615// Check for a class entry2616Boolean result = classAssertionStatus.get(className);2617if (result != null)2618return result.booleanValue();26192620// Check for most specific package entry2621int dotIndex = className.lastIndexOf('.');2622if (dotIndex < 0) { // default package2623result = packageAssertionStatus.get(null);2624if (result != null)2625return result.booleanValue();2626}2627while(dotIndex > 0) {2628className = className.substring(0, dotIndex);2629result = packageAssertionStatus.get(className);2630if (result != null)2631return result.booleanValue();2632dotIndex = className.lastIndexOf('.', dotIndex-1);2633}26342635// Return the classloader default2636return defaultAssertionStatus;2637}2638}26392640// Set up the assertions with information provided by the VM.2641// Note: Should only be called inside a synchronized block2642private void initializeJavaAssertionMaps() {2643// assert Thread.holdsLock(assertionLock);26442645classAssertionStatus = new HashMap<>();2646packageAssertionStatus = new HashMap<>();2647AssertionStatusDirectives directives = retrieveDirectives();26482649for(int i = 0; i < directives.classes.length; i++)2650classAssertionStatus.put(directives.classes[i],2651directives.classEnabled[i]);26522653for(int i = 0; i < directives.packages.length; i++)2654packageAssertionStatus.put(directives.packages[i],2655directives.packageEnabled[i]);26562657defaultAssertionStatus = directives.deflt;2658}26592660// Retrieves the assertion directives from the VM.2661private static native AssertionStatusDirectives retrieveDirectives();266226632664// -- Misc --26652666/**2667* Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)2668* associated with this ClassLoader, creating it if it doesn't already exist.2669*/2670ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() {2671ConcurrentHashMap<?, ?> map = classLoaderValueMap;2672if (map == null) {2673map = new ConcurrentHashMap<>();2674boolean set = trySetObjectField("classLoaderValueMap", map);2675if (!set) {2676// beaten by someone else2677map = classLoaderValueMap;2678}2679}2680return map;2681}26822683// the storage for ClassLoaderValue(s) associated with this ClassLoader2684private volatile ConcurrentHashMap<?, ?> classLoaderValueMap;26852686/**2687* Attempts to atomically set a volatile field in this object. Returns2688* {@code true} if not beaten by another thread. Avoids the use of2689* AtomicReferenceFieldUpdater in this class.2690*/2691private boolean trySetObjectField(String name, Object obj) {2692Unsafe unsafe = Unsafe.getUnsafe();2693Class<?> k = ClassLoader.class;2694long offset;2695offset = unsafe.objectFieldOffset(k, name);2696return unsafe.compareAndSetReference(this, offset, null, obj);2697}26982699/**2700* Called by the VM, during -Xshare:dump2701*/2702private void resetArchivedStates() {2703parallelLockMap.clear();2704packages.clear();2705package2certs.clear();2706classes.clear();2707classLoaderValueMap = null;2708}2709}27102711/*2712* A utility class that will enumerate over an array of enumerations.2713*/2714final class CompoundEnumeration<E> implements Enumeration<E> {2715private final Enumeration<E>[] enums;2716private int index;27172718public CompoundEnumeration(Enumeration<E>[] enums) {2719this.enums = enums;2720}27212722private boolean next() {2723while (index < enums.length) {2724if (enums[index] != null && enums[index].hasMoreElements()) {2725return true;2726}2727index++;2728}2729return false;2730}27312732public boolean hasMoreElements() {2733return next();2734}27352736public E nextElement() {2737if (!next()) {2738throw new NoSuchElementException();2739}2740return enums[index].nextElement();2741}2742}274327442745