1 /*
   2  * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2019, Azul Systems, Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.  Oracle designates this
   9  * particular file as subject to the "Classpath" exception as provided
  10  * by Oracle in the LICENSE file that accompanied this code.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  23  * or visit www.oracle.com if you need additional information or have any
  24  * questions.
  25  */
  26 
  27 package java.lang;
  28 
  29 import java.io.InputStream;
  30 import java.io.IOException;
  31 import java.io.UncheckedIOException;
  32 import java.io.File;
  33 import java.lang.reflect.Constructor;
  34 import java.lang.reflect.InvocationTargetException;
  35 import java.net.URL;
  36 import java.security.AccessController;
  37 import java.security.AccessControlContext;
  38 import java.security.CodeSource;
  39 import java.security.PrivilegedAction;
  40 import java.security.ProtectionDomain;
  41 import java.security.cert.Certificate;
  42 import java.util.ArrayList;
  43 import java.util.Collections;
  44 import java.util.Enumeration;
  45 import java.util.HashMap;
  46 import java.util.Map;
  47 import java.util.NoSuchElementException;
  48 import java.util.Objects;
  49 import java.util.Set;
  50 import java.util.Spliterator;
  51 import java.util.Spliterators;
  52 import java.util.WeakHashMap;
  53 import java.util.concurrent.ConcurrentHashMap;
  54 import java.util.function.Supplier;
  55 import java.util.stream.Stream;
  56 import java.util.stream.StreamSupport;
  57 
  58 import jdk.internal.loader.BootLoader;
  59 import jdk.internal.loader.BuiltinClassLoader;
  60 import jdk.internal.loader.ClassLoaders;
  61 import jdk.internal.loader.NativeLibrary;
  62 import jdk.internal.loader.NativeLibraries;
  63 import jdk.internal.perf.PerfCounter;
  64 import jdk.internal.misc.Unsafe;
  65 import jdk.internal.misc.VM;
  66 import jdk.internal.reflect.CallerSensitive;
  67 import jdk.internal.reflect.CallerSensitiveAdapter;
  68 import jdk.internal.reflect.Reflection;
  69 import jdk.internal.util.StaticProperty;
  70 import sun.reflect.misc.ReflectUtil;
  71 import sun.security.util.SecurityConstants;
  72 
  73 /**
  74  * A class loader is an object that is responsible for loading classes. The
  75  * class {@code ClassLoader} is an abstract class.  Given the <a
  76  * href="#binary-name">binary name</a> of a class, a class loader should attempt to
  77  * locate or generate data that constitutes a definition for the class.  A
  78  * typical strategy is to transform the name into a file name and then read a
  79  * "class file" of that name from a file system.
  80  *
  81  * <p> Every {@link java.lang.Class Class} object contains a {@link
  82  * Class#getClassLoader() reference} to the {@code ClassLoader} that defined
  83  * it.
  84  *
  85  * <p> {@code Class} objects for array classes are not created by class
  86  * loaders, but are created automatically as required by the Java runtime.
  87  * The class loader for an array class, as returned by {@link
  88  * Class#getClassLoader()} is the same as the class loader for its element
  89  * type; if the element type is a primitive type, then the array class has no
  90  * class loader.
  91  *
  92  * <p> Applications implement subclasses of {@code ClassLoader} in order to
  93  * extend the manner in which the Java virtual machine dynamically loads
  94  * classes.
  95  *
  96  * <p> Class loaders may typically be used by security managers to indicate
  97  * security domains.
  98  *
  99  * <p> In addition to loading classes, a class loader is also responsible for
 100  * locating resources. A resource is some data (a "{@code .class}" file,
 101  * configuration data, or an image for example) that is identified with an
 102  * abstract '/'-separated path name. Resources are typically packaged with an
 103  * application or library so that they can be located by code in the
 104  * application or library. In some cases, the resources are included so that
 105  * they can be located by other libraries.
 106  *
 107  * <p> The {@code ClassLoader} class uses a delegation model to search for
 108  * classes and resources.  Each instance of {@code ClassLoader} has an
 109  * associated parent class loader. When requested to find a class or
 110  * resource, a {@code ClassLoader} instance will usually delegate the search
 111  * for the class or resource to its parent class loader before attempting to
 112  * find the class or resource itself.
 113  *
 114  * <p> Class loaders that support concurrent loading of classes are known as
 115  * <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class
 116  * loaders and are required to register themselves at their class initialization
 117  * time by invoking the {@link
 118  * #registerAsParallelCapable ClassLoader.registerAsParallelCapable}
 119  * method. Note that the {@code ClassLoader} class is registered as parallel
 120  * capable by default. However, its subclasses still need to register themselves
 121  * if they are parallel capable.
 122  * In environments in which the delegation model is not strictly
 123  * hierarchical, class loaders need to be parallel capable, otherwise class
 124  * loading can lead to deadlocks because the loader lock is held for the
 125  * duration of the class loading process (see {@link #loadClass
 126  * loadClass} methods).
 127  *
 128  * <h2> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h2>
 129  *
 130  * The Java run-time has the following built-in class loaders:
 131  *
 132  * <ul>
 133  * <li><p>Bootstrap class loader.
 134  *     It is the virtual machine's built-in class loader, typically represented
 135  *     as {@code null}, and does not have a parent.</li>
 136  * <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}.
 137  *     The platform class loader is responsible for loading the
 138  *     <em>platform classes</em>.  Platform classes include Java SE platform APIs,
 139  *     their implementation classes and JDK-specific run-time classes that are
 140  *     defined by the platform class loader or its ancestors.
 141  *     The platform class loader can be used as the parent of a {@code ClassLoader}
 142  *     instance.
 143  *     <p> To allow for upgrading/overriding of modules defined to the platform
 144  *     class loader, and where upgraded modules read modules defined to class
 145  *     loaders other than the platform class loader and its ancestors, then
 146  *     the platform class loader may have to delegate to other class loaders,
 147  *     the application class loader for example.
 148  *     In other words, classes in named modules defined to class loaders
 149  *     other than the platform class loader and its ancestors may be visible
 150  *     to the platform class loader. </li>
 151  * <li><p>{@linkplain #getSystemClassLoader() System class loader}.
 152  *     It is also known as <em>application class loader</em> and is distinct
 153  *     from the platform class loader.
 154  *     The system class loader is typically used to define classes on the
 155  *     application class path, module path, and JDK-specific tools.
 156  *     The platform class loader is the parent or an ancestor of the system class
 157  *     loader, so the system class loader can load platform classes by delegating
 158  *     to its parent.</li>
 159  * </ul>
 160  *
 161  * <p> Normally, the Java virtual machine loads classes from the local file
 162  * system in a platform-dependent manner.
 163  * However, some classes may not originate from a file; they may originate
 164  * from other sources, such as the network, or they could be constructed by an
 165  * application.  The method {@link #defineClass(String, byte[], int, int)
 166  * defineClass} converts an array of bytes into an instance of class
 167  * {@code Class}. Instances of this newly defined class can be created using
 168  * {@link Class#newInstance Class.newInstance}.
 169  *
 170  * <p> The methods and constructors of objects created by a class loader may
 171  * reference other classes.  To determine the class(es) referred to, the Java
 172  * virtual machine invokes the {@link #loadClass loadClass} method of
 173  * the class loader that originally created the class.
 174  *
 175  * <p> For example, an application could create a network class loader to
 176  * download class files from a server.  Sample code might look like:
 177  *
 178  * <blockquote><pre>
 179  *   ClassLoader loader&nbsp;= new NetworkClassLoader(host,&nbsp;port);
 180  *   Object main&nbsp;= loader.loadClass("Main", true).newInstance();
 181  *       &nbsp;.&nbsp;.&nbsp;.
 182  * </pre></blockquote>
 183  *
 184  * <p> The network class loader subclass must define the methods {@link
 185  * #findClass findClass} and {@code loadClassData} to load a class
 186  * from the network.  Once it has downloaded the bytes that make up the class,
 187  * it should use the method {@link #defineClass defineClass} to
 188  * create a class instance.  A sample implementation is:
 189  *
 190  * <blockquote><pre>
 191  *     class NetworkClassLoader extends ClassLoader {
 192  *         String host;
 193  *         int port;
 194  *
 195  *         public Class findClass(String name) {
 196  *             byte[] b = loadClassData(name);
 197  *             return defineClass(name, b, 0, b.length);
 198  *         }
 199  *
 200  *         private byte[] loadClassData(String name) {
 201  *             // load the class data from the connection
 202  *             &nbsp;.&nbsp;.&nbsp;.
 203  *         }
 204  *     }
 205  * </pre></blockquote>
 206  *
 207  * <h3> <a id="binary-name">Binary names</a> </h3>
 208  *
 209  * <p> Any class name provided as a {@code String} parameter to methods in
 210  * {@code ClassLoader} must be a binary name as defined by
 211  * <cite>The Java Language Specification</cite>.
 212  *
 213  * <p> Examples of valid class names include:
 214  * <blockquote><pre>
 215  *   "java.lang.String"
 216  *   "javax.swing.JSpinner$DefaultEditor"
 217  *   "java.security.KeyStore$Builder$FileBuilder$1"
 218  *   "java.net.URLClassLoader$3$1"
 219  * </pre></blockquote>
 220  *
 221  * <p> Any package name provided as a {@code String} parameter to methods in
 222  * {@code ClassLoader} must be either the empty string (denoting an unnamed package)
 223  * or a fully qualified name as defined by
 224  * <cite>The Java Language Specification</cite>.
 225  *
 226  * @jls 6.7 Fully Qualified Names
 227  * @jls 13.1 The Form of a Binary
 228  * @see      #resolveClass(Class)
 229  * @since 1.0
 230  */
 231 public abstract class ClassLoader {
 232 
 233     private static native void registerNatives();
 234     static {
 235         registerNatives();
 236     }
 237 
 238     // The parent class loader for delegation
 239     // Note: VM hardcoded the offset of this field, thus all new fields
 240     // must be added *after* it.
 241     private final ClassLoader parent;
 242 
 243     // class loader name
 244     private final String name;
 245 
 246     // the unnamed module for this ClassLoader
 247     private final Module unnamedModule;
 248 
 249     // a string for exception message printing
 250     private final String nameAndId;
 251 
 252     /**
 253      * Encapsulates the set of parallel capable loader types.
 254      */
 255     private static class ParallelLoaders {
 256         private ParallelLoaders() {}
 257 
 258         // the set of parallel capable loader types
 259         private static final Set<Class<? extends ClassLoader>> loaderTypes =
 260             Collections.newSetFromMap(new WeakHashMap<>());
 261         static {
 262             synchronized (loaderTypes) { loaderTypes.add(ClassLoader.class); }
 263         }
 264 
 265         /**
 266          * Registers the given class loader type as parallel capable.
 267          * Returns {@code true} is successfully registered; {@code false} if
 268          * loader's super class is not registered.
 269          */
 270         static boolean register(Class<? extends ClassLoader> c) {
 271             synchronized (loaderTypes) {
 272                 if (loaderTypes.contains(c.getSuperclass())) {
 273                     // register the class loader as parallel capable
 274                     // if and only if all of its super classes are.
 275                     // Note: given current classloading sequence, if
 276                     // the immediate super class is parallel capable,
 277                     // all the super classes higher up must be too.
 278                     loaderTypes.add(c);
 279                     return true;
 280                 } else {
 281                     return false;
 282                 }
 283             }
 284         }
 285 
 286         /**
 287          * Returns {@code true} if the given class loader type is
 288          * registered as parallel capable.
 289          */
 290         static boolean isRegistered(Class<? extends ClassLoader> c) {
 291             synchronized (loaderTypes) {
 292                 return loaderTypes.contains(c);
 293             }
 294         }
 295     }
 296 
 297     // Maps class name to the corresponding lock object when the current
 298     // class loader is parallel capable.
 299     // Note: VM also uses this field to decide if the current class loader
 300     // is parallel capable and the appropriate lock object for class loading.
 301     private final ConcurrentHashMap<String, Object> parallelLockMap;
 302 
 303     // Maps packages to certs
 304     private final ConcurrentHashMap<String, Certificate[]> package2certs;
 305 
 306     // Shared among all packages with unsigned classes
 307     private static final Certificate[] nocerts = new Certificate[0];
 308 
 309     // The classes loaded by this class loader. The only purpose of this table
 310     // is to keep the classes from being GC'ed until the loader is GC'ed.
 311     private final ArrayList<Class<?>> classes = new ArrayList<>();
 312 
 313     // The "default" domain. Set as the default ProtectionDomain on newly
 314     // created classes.
 315     private final ProtectionDomain defaultDomain =
 316         new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
 317                              null, this, null);
 318 
 319     // Invoked by the VM to record every loaded class with this loader.
 320     void addClass(Class<?> c) {
 321         synchronized (classes) {
 322             classes.add(c);
 323         }
 324     }
 325 
 326     // The packages defined in this class loader.  Each package name is
 327     // mapped to its corresponding NamedPackage object.
 328     //
 329     // The value is a Package object if ClassLoader::definePackage,
 330     // Class::getPackage, ClassLoader::getDefinePackage(s) or
 331     // Package::getPackage(s) method is called to define it.
 332     // Otherwise, the value is a NamedPackage object.
 333     private final ConcurrentHashMap<String, NamedPackage> packages
 334             = new ConcurrentHashMap<>();
 335 
 336     /*
 337      * Returns a named package for the given module.
 338      */
 339     private NamedPackage getNamedPackage(String pn, Module m) {
 340         NamedPackage p = packages.get(pn);
 341         if (p == null) {
 342             p = new NamedPackage(pn, m);
 343 
 344             NamedPackage value = packages.putIfAbsent(pn, p);
 345             if (value != null) {
 346                 // Package object already be defined for the named package
 347                 p = value;
 348                 // if definePackage is called by this class loader to define
 349                 // a package in a named module, this will return Package
 350                 // object of the same name.  Package object may contain
 351                 // unexpected information but it does not impact the runtime.
 352                 // this assertion may be helpful for troubleshooting
 353                 assert value.module() == m;
 354             }
 355         }
 356         return p;
 357     }
 358 
 359     private static Void checkCreateClassLoader() {
 360         return checkCreateClassLoader(null);
 361     }
 362 
 363     private static Void checkCreateClassLoader(String name) {
 364         if (name != null && name.isEmpty()) {
 365             throw new IllegalArgumentException("name must be non-empty or null");
 366         }
 367 
 368         @SuppressWarnings("removal")
 369         SecurityManager security = System.getSecurityManager();
 370         if (security != null) {
 371             security.checkCreateClassLoader();
 372         }
 373         return null;
 374     }
 375 
 376     private ClassLoader(Void unused, String name, ClassLoader parent) {
 377         this.name = name;
 378         this.parent = parent;
 379         this.unnamedModule = new Module(this);
 380         if (ParallelLoaders.isRegistered(this.getClass())) {
 381             parallelLockMap = new ConcurrentHashMap<>();
 382             assertionLock = new Object();
 383         } else {
 384             // no finer-grained lock; lock on the classloader instance
 385             parallelLockMap = null;
 386             assertionLock = this;
 387         }
 388         this.package2certs = new ConcurrentHashMap<>();
 389         this.nameAndId = nameAndId(this);
 390     }
 391 
 392     /**
 393      * If the defining loader has a name explicitly set then
 394      *       '<loader-name>' @<id>
 395      * If the defining loader has no name then
 396      *       <qualified-class-name> @<id>
 397      * If it's built-in loader then omit `@<id>` as there is only one instance.
 398      */
 399     private static String nameAndId(ClassLoader ld) {
 400         String nid = ld.getName() != null ? "\'" + ld.getName() + "\'"
 401                                           : ld.getClass().getName();
 402         if (!(ld instanceof BuiltinClassLoader)) {
 403             String id = Integer.toHexString(System.identityHashCode(ld));
 404             nid = nid + " @" + id;
 405         }
 406         return nid;
 407     }
 408 
 409     // Returns nameAndId string for exception message printing
 410     String nameAndId() {
 411         return nameAndId;
 412     }
 413 
 414     /**
 415      * Creates a new class loader of the specified name and using the
 416      * specified parent class loader for delegation.
 417      *
 418      * @apiNote If the parent is specified as {@code null} (for the
 419      * bootstrap class loader) then there is no guarantee that all platform
 420      * classes are visible.
 421      *
 422      * @param  name   class loader name; or {@code null} if not named
 423      * @param  parent the parent class loader
 424      *
 425      * @throws IllegalArgumentException if the given name is empty.
 426      *
 427      * @throws SecurityException
 428      *         If a security manager exists and its
 429      *         {@link SecurityManager#checkCreateClassLoader()}
 430      *         method doesn't allow creation of a new class loader.
 431      *
 432      * @since  9
 433      */
 434     @SuppressWarnings("this-escape")
 435     protected ClassLoader(String name, ClassLoader parent) {
 436         this(checkCreateClassLoader(name), name, parent);
 437     }
 438 
 439     /**
 440      * Creates a new class loader using the specified parent class loader for
 441      * delegation.
 442      *
 443      * <p> If there is a security manager, its {@link
 444      * SecurityManager#checkCreateClassLoader() checkCreateClassLoader} method
 445      * is invoked.  This may result in a security exception.  </p>
 446      *
 447      * @apiNote If the parent is specified as {@code null} (for the
 448      * bootstrap class loader) then there is no guarantee that all platform
 449      * classes are visible.
 450      *
 451      * @param  parent
 452      *         The parent class loader
 453      *
 454      * @throws SecurityException
 455      *         If a security manager exists and its
 456      *         {@code checkCreateClassLoader} method doesn't allow creation
 457      *         of a new class loader.
 458      *
 459      * @since  1.2
 460      */
 461     @SuppressWarnings("this-escape")
 462     protected ClassLoader(ClassLoader parent) {
 463         this(checkCreateClassLoader(), null, parent);
 464     }
 465 
 466     /**
 467      * Creates a new class loader using the {@code ClassLoader} returned by
 468      * the method {@link #getSystemClassLoader()
 469      * getSystemClassLoader()} as the parent class loader.
 470      *
 471      * <p> If there is a security manager, its {@link
 472      * SecurityManager#checkCreateClassLoader()
 473      * checkCreateClassLoader} method is invoked.  This may result in
 474      * a security exception.  </p>
 475      *
 476      * @throws  SecurityException
 477      *          If a security manager exists and its
 478      *          {@code checkCreateClassLoader} method doesn't allow creation
 479      *          of a new class loader.
 480      */
 481     @SuppressWarnings("this-escape")
 482     protected ClassLoader() {
 483         this(checkCreateClassLoader(), null, getSystemClassLoader());
 484     }
 485 
 486     /**
 487      * Returns the name of this class loader or {@code null} if
 488      * this class loader is not named.
 489      *
 490      * @apiNote This method is non-final for compatibility.  If this
 491      * method is overridden, this method must return the same name
 492      * as specified when this class loader was instantiated.
 493      *
 494      * @return name of this class loader; or {@code null} if
 495      * this class loader is not named.
 496      *
 497      * @since 9
 498      */
 499     public String getName() {
 500         return name;
 501     }
 502 
 503     // package-private used by StackTraceElement to avoid
 504     // calling the overridable getName method
 505     final String name() {
 506         return name;
 507     }
 508 
 509     // -- Class --
 510 
 511     /**
 512      * Loads the class with the specified <a href="#binary-name">binary name</a>.
 513      * This method searches for classes in the same manner as the {@link
 514      * #loadClass(String, boolean)} method.  It is invoked by the Java virtual
 515      * machine to resolve class references.  Invoking this method is equivalent
 516      * to invoking {@link #loadClass(String, boolean) loadClass(name,
 517      * false)}.
 518      *
 519      * @param   name
 520      *          The <a href="#binary-name">binary name</a> of the class
 521      *
 522      * @return  The resulting {@code Class} object
 523      *
 524      * @throws  ClassNotFoundException
 525      *          If the class was not found
 526      */
 527     public Class<?> loadClass(String name) throws ClassNotFoundException {
 528         return loadClass(name, false);
 529     }
 530 
 531     /**
 532      * Loads the class with the specified <a href="#binary-name">binary name</a>.  The
 533      * default implementation of this method searches for classes in the
 534      * following order:
 535      *
 536      * <ol>
 537      *
 538      *   <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
 539      *   has already been loaded.  </p></li>
 540      *
 541      *   <li><p> Invoke the {@link #loadClass(String) loadClass} method
 542      *   on the parent class loader.  If the parent is {@code null} the class
 543      *   loader built into the virtual machine is used, instead.  </p></li>
 544      *
 545      *   <li><p> Invoke the {@link #findClass(String)} method to find the
 546      *   class.  </p></li>
 547      *
 548      * </ol>
 549      *
 550      * <p> If the class was found using the above steps, and the
 551      * {@code resolve} flag is true, this method will then invoke the {@link
 552      * #resolveClass(Class)} method on the resulting {@code Class} object.
 553      *
 554      * <p> Subclasses of {@code ClassLoader} are encouraged to override {@link
 555      * #findClass(String)}, rather than this method.  </p>
 556      *
 557      * <p> Unless overridden, this method synchronizes on the result of
 558      * {@link #getClassLoadingLock getClassLoadingLock} method
 559      * during the entire class loading process.
 560      *
 561      * @param   name
 562      *          The <a href="#binary-name">binary name</a> of the class
 563      *
 564      * @param   resolve
 565      *          If {@code true} then resolve the class
 566      *
 567      * @return  The resulting {@code Class} object
 568      *
 569      * @throws  ClassNotFoundException
 570      *          If the class could not be found
 571      */
 572     protected Class<?> loadClass(String name, boolean resolve)
 573         throws ClassNotFoundException
 574     {
 575         synchronized (getClassLoadingLock(name)) {
 576             // First, check if the class has already been loaded
 577             Class<?> c = findLoadedClass(name);
 578             if (c == null) {
 579                 long t0 = System.nanoTime();
 580                 try {
 581                     if (parent != null) {
 582                         c = parent.loadClass(name, false);
 583                     } else {
 584                         c = findBootstrapClassOrNull(name);
 585                     }
 586                 } catch (ClassNotFoundException e) {
 587                     // ClassNotFoundException thrown if class not found
 588                     // from the non-null parent class loader
 589                 }
 590 
 591                 if (c == null) {
 592                     // If still not found, then invoke findClass in order
 593                     // to find the class.
 594                     long t1 = System.nanoTime();
 595                     c = findClass(name);
 596 
 597                     // this is the defining class loader; record the stats
 598                     PerfCounter.getParentDelegationTime().addTime(t1 - t0);
 599                     PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
 600                     PerfCounter.getFindClasses().increment();
 601                 }
 602             }
 603             if (resolve) {
 604                 resolveClass(c);
 605             }
 606             return c;
 607         }
 608     }
 609 
 610     /**
 611      * Loads the class with the specified <a href="#binary-name">binary name</a>
 612      * in a module defined to this class loader.  This method returns {@code null}
 613      * if the class could not be found.
 614      *
 615      * @apiNote This method does not delegate to the parent class loader.
 616      *
 617      * @implSpec The default implementation of this method searches for classes
 618      * in the following order:
 619      *
 620      * <ol>
 621      *   <li>Invoke {@link #findLoadedClass(String)} to check if the class
 622      *   has already been loaded.</li>
 623      *   <li>Invoke the {@link #findClass(String, String)} method to find the
 624      *   class in the given module.</li>
 625      * </ol>
 626      *
 627      * @param  module
 628      *         The module
 629      * @param  name
 630      *         The <a href="#binary-name">binary name</a> of the class
 631      *
 632      * @return The resulting {@code Class} object in a module defined by
 633      *         this class loader, or {@code null} if the class could not be found.
 634      */
 635     final Class<?> loadClass(Module module, String name) {
 636         synchronized (getClassLoadingLock(name)) {
 637             // First, check if the class has already been loaded
 638             Class<?> c = findLoadedClass(name);
 639             if (c == null) {
 640                 c = findClass(module.getName(), name);
 641             }
 642             if (c != null && c.getModule() == module) {
 643                 return c;
 644             } else {
 645                 return null;
 646             }
 647         }
 648     }
 649 
 650     /**
 651      * Returns the lock object for class loading operations.
 652      *
 653      * @implSpec
 654      * If this {@code ClassLoader} object is registered as parallel capable,
 655      * this method returns a dedicated object associated with the specified
 656      * class name. Otherwise, this method returns this {@code ClassLoader} object.
 657      *
 658      * @apiNote
 659      * This method allows parallel capable class loaders to implement
 660      * finer-grained locking schemes such that multiple threads may load classes
 661      * concurrently without deadlocks.  For non-parallel-capable class loaders,
 662      * the {@code ClassLoader} object is synchronized on during the class loading
 663      * operations.  Class loaders with non-hierarchical delegation should be
 664      * {@linkplain #registerAsParallelCapable() registered as parallel capable}
 665      * to prevent deadlocks.
 666      *
 667      * @param  className
 668      *         The name of the to-be-loaded class
 669      *
 670      * @return the lock for class loading operations
 671      *
 672      * @throws NullPointerException
 673      *         If registered as parallel capable and {@code className} is {@code null}
 674      *
 675      * @see #loadClass(String, boolean)
 676      *
 677      * @since  1.7
 678      */
 679     protected Object getClassLoadingLock(String className) {
 680         Object lock = this;
 681         if (parallelLockMap != null) {
 682             Object newLock = new Object();
 683             lock = parallelLockMap.putIfAbsent(className, newLock);
 684             if (lock == null) {
 685                 lock = newLock;
 686             }
 687         }
 688         return lock;
 689     }
 690 
 691     // Invoked by the VM after loading class with this loader.
 692     @SuppressWarnings("removal")
 693     private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
 694         final SecurityManager sm = System.getSecurityManager();
 695         if (sm != null) {
 696             if (ReflectUtil.isNonPublicProxyClass(cls)) {
 697                 for (Class<?> intf: cls.getInterfaces()) {
 698                     checkPackageAccess(intf, pd);
 699                 }
 700                 return;
 701             }
 702 
 703             final String packageName = cls.getPackageName();
 704             if (!packageName.isEmpty()) {
 705                 AccessController.doPrivileged(new PrivilegedAction<>() {
 706                     public Void run() {
 707                         sm.checkPackageAccess(packageName);
 708                         return null;
 709                     }
 710                 }, new AccessControlContext(new ProtectionDomain[] {pd}));
 711             }
 712         }
 713     }
 714 
 715     /**
 716      * Finds the class with the specified <a href="#binary-name">binary name</a>.
 717      * This method should be overridden by class loader implementations that
 718      * follow the delegation model for loading classes, and will be invoked by
 719      * the {@link #loadClass loadClass} method after checking the
 720      * parent class loader for the requested class.
 721      *
 722      * @implSpec The default implementation throws {@code ClassNotFoundException}.
 723      *
 724      * @param   name
 725      *          The <a href="#binary-name">binary name</a> of the class
 726      *
 727      * @return  The resulting {@code Class} object
 728      *
 729      * @throws  ClassNotFoundException
 730      *          If the class could not be found
 731      *
 732      * @since  1.2
 733      */
 734     protected Class<?> findClass(String name) throws ClassNotFoundException {
 735         throw new ClassNotFoundException(name);
 736     }
 737 
 738     /**
 739      * Finds the class with the given <a href="#binary-name">binary name</a>
 740      * in a module defined to this class loader.
 741      * Class loader implementations that support loading from modules
 742      * should override this method.
 743      *
 744      * @apiNote This method returns {@code null} rather than throwing
 745      *          {@code ClassNotFoundException} if the class could not be found.
 746      *
 747      * @implSpec The default implementation attempts to find the class by
 748      * invoking {@link #findClass(String)} when the {@code moduleName} is
 749      * {@code null}. It otherwise returns {@code null}.
 750      *
 751      * @param  moduleName
 752      *         The module name; or {@code null} to find the class in the
 753      *         {@linkplain #getUnnamedModule() unnamed module} for this
 754      *         class loader
 755      * @param  name
 756      *         The <a href="#binary-name">binary name</a> of the class
 757      *
 758      * @return The resulting {@code Class} object, or {@code null}
 759      *         if the class could not be found.
 760      *
 761      * @since 9
 762      */
 763     protected Class<?> findClass(String moduleName, String name) {
 764         if (moduleName == null) {
 765             try {
 766                 return findClass(name);
 767             } catch (ClassNotFoundException ignore) { }
 768         }
 769         return null;
 770     }
 771 
 772 
 773     /**
 774      * Converts an array of bytes into an instance of class {@code Class}.
 775      * Before the {@code Class} can be used it must be resolved.  This method
 776      * is deprecated in favor of the version that takes a <a
 777      * href="#binary-name">binary name</a> as its first argument, and is more secure.
 778      *
 779      * @param  b
 780      *         The bytes that make up the class data.  The bytes in positions
 781      *         {@code off} through {@code off+len-1} should have the format
 782      *         of a valid class file as defined by
 783      *         <cite>The Java Virtual Machine Specification</cite>.
 784      *
 785      * @param  off
 786      *         The start offset in {@code b} of the class data
 787      *
 788      * @param  len
 789      *         The length of the class data
 790      *
 791      * @return  The {@code Class} object that was created from the specified
 792      *          class data
 793      *
 794      * @throws  ClassFormatError
 795      *          If the data did not contain a valid class
 796      *
 797      * @throws  IndexOutOfBoundsException
 798      *          If either {@code off} or {@code len} is negative, or if
 799      *          {@code off+len} is greater than {@code b.length}.
 800      *
 801      * @throws  SecurityException
 802      *          If an attempt is made to add this class to a package that
 803      *          contains classes that were signed by a different set of
 804      *          certificates than this class, or if an attempt is made
 805      *          to define a class in a package with a fully-qualified name
 806      *          that starts with "{@code java.}".
 807      *
 808      * @see  #loadClass(String, boolean)
 809      * @see  #resolveClass(Class)
 810      *
 811      * @deprecated  Replaced by {@link #defineClass(String, byte[], int, int)
 812      * defineClass(String, byte[], int, int)}
 813      */
 814     @Deprecated(since="1.1")
 815     protected final Class<?> defineClass(byte[] b, int off, int len)
 816         throws ClassFormatError
 817     {
 818         return defineClass(null, b, off, len, null);
 819     }
 820 
 821     /**
 822      * Converts an array of bytes into an instance of class {@code Class}.
 823      * Before the {@code Class} can be used it must be resolved.
 824      *
 825      * <p> This method assigns a default {@link java.security.ProtectionDomain
 826      * ProtectionDomain} to the newly defined class.  The
 827      * {@code ProtectionDomain} is effectively granted the same set of
 828      * permissions returned when {@link
 829      * java.security.Policy#getPermissions(java.security.CodeSource)
 830      * Policy.getPolicy().getPermissions(new CodeSource(null, null))}
 831      * is invoked.  The default protection domain is created on the first invocation
 832      * of {@link #defineClass(String, byte[], int, int) defineClass},
 833      * and re-used on subsequent invocations.
 834      *
 835      * <p> To assign a specific {@code ProtectionDomain} to the class, use
 836      * the {@link #defineClass(String, byte[], int, int,
 837      * java.security.ProtectionDomain) defineClass} method that takes a
 838      * {@code ProtectionDomain} as one of its arguments.  </p>
 839      *
 840      * <p>
 841      * This method defines a package in this class loader corresponding to the
 842      * package of the {@code Class} (if such a package has not already been defined
 843      * in this class loader). The name of the defined package is derived from
 844      * the <a href="#binary-name">binary name</a> of the class specified by
 845      * the byte array {@code b}.
 846      * Other properties of the defined package are as specified by {@link Package}.
 847      *
 848      * @param  name
 849      *         The expected <a href="#binary-name">binary name</a> of the class, or
 850      *         {@code null} if not known
 851      *
 852      * @param  b
 853      *         The bytes that make up the class data.  The bytes in positions
 854      *         {@code off} through {@code off+len-1} should have the format
 855      *         of a valid class file as defined by
 856      *         <cite>The Java Virtual Machine Specification</cite>.
 857      *
 858      * @param  off
 859      *         The start offset in {@code b} of the class data
 860      *
 861      * @param  len
 862      *         The length of the class data
 863      *
 864      * @return  The {@code Class} object that was created from the specified
 865      *          class data.
 866      *
 867      * @throws  ClassFormatError
 868      *          If the data did not contain a valid class
 869      *
 870      * @throws  IndexOutOfBoundsException
 871      *          If either {@code off} or {@code len} is negative, or if
 872      *          {@code off+len} is greater than {@code b.length}.
 873      *
 874      * @throws  SecurityException
 875      *          If an attempt is made to add this class to a package that
 876      *          contains classes that were signed by a different set of
 877      *          certificates than this class (which is unsigned), or if
 878      *          {@code name} begins with "{@code java.}".
 879      *
 880      * @see  #loadClass(String, boolean)
 881      * @see  #resolveClass(Class)
 882      * @see  java.security.CodeSource
 883      * @see  java.security.SecureClassLoader
 884      *
 885      * @since  1.1
 886      */
 887     protected final Class<?> defineClass(String name, byte[] b, int off, int len)
 888         throws ClassFormatError
 889     {
 890         return defineClass(name, b, off, len, null);
 891     }
 892 
 893     /* Determine protection domain, and check that:
 894         - not define java.* class,
 895         - signer of this class matches signers for the rest of the classes in
 896           package.
 897     */
 898     private ProtectionDomain preDefineClass(String name,
 899                                             ProtectionDomain pd)
 900     {
 901         if (!checkName(name))
 902             throw new NoClassDefFoundError("IllegalName: " + name);
 903 
 904         // Note:  Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
 905         // relies on the fact that spoofing is impossible if a class has a name
 906         // of the form "java.*"
 907         if ((name != null) && name.startsWith("java.")
 908                 && this != getBuiltinPlatformClassLoader()) {
 909             throw new SecurityException
 910                 ("Prohibited package name: " +
 911                  name.substring(0, name.lastIndexOf('.')));
 912         }
 913         if (pd == null) {
 914             pd = defaultDomain;
 915         }
 916 
 917         if (name != null) {
 918             checkCerts(name, pd.getCodeSource());
 919         }
 920 
 921         return pd;
 922     }
 923 
 924     private String defineClassSourceLocation(ProtectionDomain pd) {
 925         CodeSource cs = pd.getCodeSource();
 926         String source = null;
 927         if (cs != null && cs.getLocation() != null) {
 928             source = cs.getLocation().toString();
 929         }
 930         return source;
 931     }
 932 
 933     private void postDefineClass(Class<?> c, ProtectionDomain pd) {
 934         // define a named package, if not present
 935         getNamedPackage(c.getPackageName(), c.getModule());
 936 
 937         if (pd.getCodeSource() != null) {
 938             Certificate certs[] = pd.getCodeSource().getCertificates();
 939             if (certs != null)
 940                 setSigners(c, certs);
 941         }
 942     }
 943 
 944     /**
 945      * Converts an array of bytes into an instance of class {@code Class},
 946      * with a given {@code ProtectionDomain}.
 947      *
 948      * <p> If the given {@code ProtectionDomain} is {@code null},
 949      * then a default protection domain will be assigned to the class as specified
 950      * in the documentation for {@link #defineClass(String, byte[], int, int)}.
 951      * Before the class can be used it must be resolved.
 952      *
 953      * <p> The first class defined in a package determines the exact set of
 954      * certificates that all subsequent classes defined in that package must
 955      * contain.  The set of certificates for a class is obtained from the
 956      * {@link java.security.CodeSource CodeSource} within the
 957      * {@code ProtectionDomain} of the class.  Any classes added to that
 958      * package must contain the same set of certificates or a
 959      * {@code SecurityException} will be thrown.  Note that if
 960      * {@code name} is {@code null}, this check is not performed.
 961      * You should always pass in the <a href="#binary-name">binary name</a> of the
 962      * class you are defining as well as the bytes.  This ensures that the
 963      * class you are defining is indeed the class you think it is.
 964      *
 965      * <p> If the specified {@code name} begins with "{@code java.}", it can
 966      * only be defined by the {@linkplain #getPlatformClassLoader()
 967      * platform class loader} or its ancestors; otherwise {@code SecurityException}
 968      * will be thrown.  If {@code name} is not {@code null}, it must be equal to
 969      * the <a href="#binary-name">binary name</a> of the class
 970      * specified by the byte array {@code b}, otherwise a {@link
 971      * NoClassDefFoundError NoClassDefFoundError} will be thrown.
 972      *
 973      * <p> This method defines a package in this class loader corresponding to the
 974      * package of the {@code Class} (if such a package has not already been defined
 975      * in this class loader). The name of the defined package is derived from
 976      * the <a href="#binary-name">binary name</a> of the class specified by
 977      * the byte array {@code b}.
 978      * Other properties of the defined package are as specified by {@link Package}.
 979      *
 980      * @param  name
 981      *         The expected <a href="#binary-name">binary name</a> of the class, or
 982      *         {@code null} if not known
 983      *
 984      * @param  b
 985      *         The bytes that make up the class data. The bytes in positions
 986      *         {@code off} through {@code off+len-1} should have the format
 987      *         of a valid class file as defined by
 988      *         <cite>The Java Virtual Machine Specification</cite>.
 989      *
 990      * @param  off
 991      *         The start offset in {@code b} of the class data
 992      *
 993      * @param  len
 994      *         The length of the class data
 995      *
 996      * @param  protectionDomain
 997      *         The {@code ProtectionDomain} of the class
 998      *
 999      * @return  The {@code Class} object created from the data,
1000      *          and {@code ProtectionDomain}.
1001      *
1002      * @throws  ClassFormatError
1003      *          If the data did not contain a valid class
1004      *
1005      * @throws  NoClassDefFoundError
1006      *          If {@code name} is not {@code null} and not equal to the
1007      *          <a href="#binary-name">binary name</a> of the class specified by {@code b}
1008      *
1009      * @throws  IndexOutOfBoundsException
1010      *          If either {@code off} or {@code len} is negative, or if
1011      *          {@code off+len} is greater than {@code b.length}.
1012      *
1013      * @throws  SecurityException
1014      *          If an attempt is made to add this class to a package that
1015      *          contains classes that were signed by a different set of
1016      *          certificates than this class, or if {@code name} begins with
1017      *          "{@code java.}" and this class loader is not the platform
1018      *          class loader or its ancestor.
1019      */
1020     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
1021                                          ProtectionDomain protectionDomain)
1022         throws ClassFormatError
1023     {
1024         protectionDomain = preDefineClass(name, protectionDomain);
1025         String source = defineClassSourceLocation(protectionDomain);
1026         Class<?> c = defineClass1(this, name, b, off, len, protectionDomain, source);
1027         postDefineClass(c, protectionDomain);
1028         return c;
1029     }
1030 
1031     /**
1032      * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
1033      * of class {@code Class}, with the given {@code ProtectionDomain}.
1034      * If the given {@code ProtectionDomain} is {@code null}, then a default
1035      * protection domain will be assigned to the class as
1036      * specified in the documentation for {@link #defineClass(String, byte[],
1037      * int, int)}.  Before the class can be used it must be resolved.
1038      *
1039      * <p>The rules about the first class defined in a package determining the
1040      * set of certificates for the package, the restrictions on class names,
1041      * and the defined package of the class
1042      * are identical to those specified in the documentation for {@link
1043      * #defineClass(String, byte[], int, int, ProtectionDomain)}.
1044      *
1045      * <p> An invocation of this method of the form
1046      * <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,}
1047      * <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same
1048      * result as the statements
1049      *
1050      *<p> <code>
1051      * ...<br>
1052      * byte[] temp = new byte[bBuffer.{@link
1053      * java.nio.ByteBuffer#remaining remaining}()];<br>
1054      *     bBuffer.{@link java.nio.ByteBuffer#get(byte[])
1055      * get}(temp);<br>
1056      *     return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
1057      * cl.defineClass}(name, temp, 0,
1058      * temp.length, pd);<br>
1059      * </code></p>
1060      *
1061      * @param  name
1062      *         The expected <a href="#binary-name">binary name</a>. of the class, or
1063      *         {@code null} if not known
1064      *
1065      * @param  b
1066      *         The bytes that make up the class data. The bytes from positions
1067      *         {@code b.position()} through {@code b.position() + b.limit() -1
1068      *         } should have the format of a valid class file as defined by
1069      *         <cite>The Java Virtual Machine Specification</cite>.
1070      *
1071      * @param  protectionDomain
1072      *         The {@code ProtectionDomain} of the class, or {@code null}.
1073      *
1074      * @return  The {@code Class} object created from the data,
1075      *          and {@code ProtectionDomain}.
1076      *
1077      * @throws  ClassFormatError
1078      *          If the data did not contain a valid class.
1079      *
1080      * @throws  NoClassDefFoundError
1081      *          If {@code name} is not {@code null} and not equal to the
1082      *          <a href="#binary-name">binary name</a> of the class specified by {@code b}
1083      *
1084      * @throws  SecurityException
1085      *          If an attempt is made to add this class to a package that
1086      *          contains classes that were signed by a different set of
1087      *          certificates than this class, or if {@code name} begins with
1088      *          "{@code java.}".
1089      *
1090      * @see      #defineClass(String, byte[], int, int, ProtectionDomain)
1091      *
1092      * @since  1.5
1093      */
1094     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
1095                                          ProtectionDomain protectionDomain)
1096         throws ClassFormatError
1097     {
1098         int len = b.remaining();
1099 
1100         // Use byte[] if not a direct ByteBuffer:
1101         if (!b.isDirect()) {
1102             if (b.hasArray()) {
1103                 return defineClass(name, b.array(),
1104                                    b.position() + b.arrayOffset(), len,
1105                                    protectionDomain);
1106             } else {
1107                 // no array, or read-only array
1108                 byte[] tb = new byte[len];
1109                 b.get(tb);  // get bytes out of byte buffer.
1110                 return defineClass(name, tb, 0, len, protectionDomain);
1111             }
1112         }
1113 
1114         protectionDomain = preDefineClass(name, protectionDomain);
1115         String source = defineClassSourceLocation(protectionDomain);
1116         Class<?> c = defineClass2(this, name, b, b.position(), len, protectionDomain, source);
1117         postDefineClass(c, protectionDomain);
1118         return c;
1119     }
1120 
1121     static native Class<?> defineClass1(ClassLoader loader, String name, byte[] b, int off, int len,
1122                                         ProtectionDomain pd, String source);
1123 
1124     static native Class<?> defineClass2(ClassLoader loader, String name, java.nio.ByteBuffer b,
1125                                         int off, int len, ProtectionDomain pd,
1126                                         String source);
1127 
1128     /**
1129      * Defines a class of the given flags via Lookup.defineClass.
1130      *
1131      * @param loader the defining loader
1132      * @param lookup nest host of the Class to be defined
1133      * @param name the binary name or {@code null} if not findable
1134      * @param b class bytes
1135      * @param off the start offset in {@code b} of the class bytes
1136      * @param len the length of the class bytes
1137      * @param pd protection domain
1138      * @param initialize initialize the class
1139      * @param flags flags
1140      * @param classData class data
1141      */
1142     static native Class<?> defineClass0(ClassLoader loader,
1143                                         Class<?> lookup,
1144                                         String name,
1145                                         byte[] b, int off, int len,
1146                                         ProtectionDomain pd,
1147                                         boolean initialize,
1148                                         int flags,
1149                                         Object classData);
1150 
1151     // true if the name is null or has the potential to be a valid binary name
1152     private static boolean checkName(String name) {
1153         if ((name == null) || (name.isEmpty()))
1154             return true;
1155         if ((name.indexOf('/') != -1) || (name.charAt(0) == '['))
1156             return false;
1157         return true;
1158     }
1159 
1160     private void checkCerts(String name, CodeSource cs) {
1161         int i = name.lastIndexOf('.');
1162         String pname = (i == -1) ? "" : name.substring(0, i);
1163 
1164         Certificate[] certs = null;
1165         if (cs != null) {
1166             certs = cs.getCertificates();
1167         }
1168         certs = certs == null ? nocerts : certs;
1169         Certificate[] pcerts = package2certs.putIfAbsent(pname, certs);
1170         if (pcerts != null && !compareCerts(pcerts, certs)) {
1171             throw new SecurityException("class \"" + name
1172                 + "\"'s signer information does not match signer information"
1173                 + " of other classes in the same package");
1174         }
1175     }
1176 
1177     /**
1178      * check to make sure the certs for the new class (certs) are the same as
1179      * the certs for the first class inserted in the package (pcerts)
1180      */
1181     private boolean compareCerts(Certificate[] pcerts, Certificate[] certs) {
1182         // empty array fast-path
1183         if (certs.length == 0)
1184             return pcerts.length == 0;
1185 
1186         // the length must be the same at this point
1187         if (certs.length != pcerts.length)
1188             return false;
1189 
1190         // go through and make sure all the certs in one array
1191         // are in the other and vice-versa.
1192         boolean match;
1193         for (Certificate cert : certs) {
1194             match = false;
1195             for (Certificate pcert : pcerts) {
1196                 if (cert.equals(pcert)) {
1197                     match = true;
1198                     break;
1199                 }
1200             }
1201             if (!match) return false;
1202         }
1203 
1204         // now do the same for pcerts
1205         for (Certificate pcert : pcerts) {
1206             match = false;
1207             for (Certificate cert : certs) {
1208                 if (pcert.equals(cert)) {
1209                     match = true;
1210                     break;
1211                 }
1212             }
1213             if (!match) return false;
1214         }
1215 
1216         return true;
1217     }
1218 
1219     /**
1220      * Links the specified class.  This (misleadingly named) method may be
1221      * used by a class loader to link a class.  If the class {@code c} has
1222      * already been linked, then this method simply returns. Otherwise, the
1223      * class is linked as described in the "Execution" chapter of
1224      * <cite>The Java Language Specification</cite>.
1225      *
1226      * @param  c
1227      *         The class to link
1228      *
1229      * @throws  NullPointerException
1230      *          If {@code c} is {@code null}.
1231      *
1232      * @see  #defineClass(String, byte[], int, int)
1233      */
1234     protected final void resolveClass(Class<?> c) {
1235         if (c == null) {
1236             throw new NullPointerException();
1237         }
1238     }
1239 
1240     /**
1241      * Finds a class with the specified <a href="#binary-name">binary name</a>,
1242      * loading it if necessary.
1243      *
1244      * <p> This method loads the class through the system class loader (see
1245      * {@link #getSystemClassLoader()}).  The {@code Class} object returned
1246      * might have more than one {@code ClassLoader} associated with it.
1247      * Subclasses of {@code ClassLoader} need not usually invoke this method,
1248      * because most class loaders need to override just {@link
1249      * #findClass(String)}.  </p>
1250      *
1251      * @param  name
1252      *         The <a href="#binary-name">binary name</a> of the class
1253      *
1254      * @return  The {@code Class} object for the specified {@code name}
1255      *
1256      * @throws  ClassNotFoundException
1257      *          If the class could not be found
1258      *
1259      * @see  #ClassLoader(ClassLoader)
1260      * @see  #getParent()
1261      */
1262     protected final Class<?> findSystemClass(String name)
1263         throws ClassNotFoundException
1264     {
1265         return getSystemClassLoader().loadClass(name);
1266     }
1267 
1268     /**
1269      * Returns a class loaded by the bootstrap class loader;
1270      * or return null if not found.
1271      */
1272     static Class<?> findBootstrapClassOrNull(String name) {
1273         if (!checkName(name)) return null;
1274 
1275         return findBootstrapClass(name);
1276     }
1277 
1278     // return null if not found
1279     private static native Class<?> findBootstrapClass(String name);
1280 
1281     /**
1282      * Returns the class with the given <a href="#binary-name">binary name</a> if this
1283      * loader has been recorded by the Java virtual machine as an initiating
1284      * loader of a class with that <a href="#binary-name">binary name</a>.  Otherwise
1285      * {@code null} is returned.
1286      *
1287      * @param  name
1288      *         The <a href="#binary-name">binary name</a> of the class
1289      *
1290      * @return  The {@code Class} object, or {@code null} if the class has
1291      *          not been loaded
1292      *
1293      * @since  1.1
1294      */
1295     protected final Class<?> findLoadedClass(String name) {
1296         if (!checkName(name))
1297             return null;
1298         return findLoadedClass0(name);
1299     }
1300 
1301     private final native Class<?> findLoadedClass0(String name);
1302 
1303     /**
1304      * Sets the signers of a class.  This should be invoked after defining a
1305      * class.
1306      *
1307      * @param  c
1308      *         The {@code Class} object
1309      *
1310      * @param  signers
1311      *         The signers for the class
1312      *
1313      * @since  1.1
1314      */
1315     protected final void setSigners(Class<?> c, Object[] signers) {
1316         c.setSigners(signers);
1317     }
1318 
1319 
1320     // -- Resources --
1321 
1322     /**
1323      * Returns a URL to a resource in a module defined to this class loader.
1324      * Class loader implementations that support loading from modules
1325      * should override this method.
1326      *
1327      * @apiNote This method is the basis for the {@link
1328      * Class#getResource Class.getResource}, {@link Class#getResourceAsStream
1329      * Class.getResourceAsStream}, and {@link Module#getResourceAsStream
1330      * Module.getResourceAsStream} methods. It is not subject to the rules for
1331      * encapsulation specified by {@code Module.getResourceAsStream}.
1332      *
1333      * @implSpec The default implementation attempts to find the resource by
1334      * invoking {@link #findResource(String)} when the {@code moduleName} is
1335      * {@code null}. It otherwise returns {@code null}.
1336      *
1337      * @param  moduleName
1338      *         The module name; or {@code null} to find a resource in the
1339      *         {@linkplain #getUnnamedModule() unnamed module} for this
1340      *         class loader
1341      * @param  name
1342      *         The resource name
1343      *
1344      * @return A URL to the resource; {@code null} if the resource could not be
1345      *         found, a URL could not be constructed to locate the resource,
1346      *         access to the resource is denied by the security manager, or
1347      *         there isn't a module of the given name defined to the class
1348      *         loader.
1349      *
1350      * @throws IOException
1351      *         If I/O errors occur
1352      *
1353      * @see java.lang.module.ModuleReader#find(String)
1354      * @since 9
1355      */
1356     protected URL findResource(String moduleName, String name) throws IOException {
1357         if (moduleName == null) {
1358             return findResource(name);
1359         } else {
1360             return null;
1361         }
1362     }
1363 
1364     /**
1365      * Finds the resource with the given name.  A resource is some data
1366      * (images, audio, text, etc) that can be accessed by class code in a way
1367      * that is independent of the location of the code.
1368      *
1369      * <p> The name of a resource is a '{@code /}'-separated path name that
1370      * identifies the resource. </p>
1371      *
1372      * <p> Resources in named modules are subject to the encapsulation rules
1373      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1374      * Additionally, and except for the special case where the resource has a
1375      * name ending with "{@code .class}", this method will only find resources in
1376      * packages of named modules when the package is {@link Module#isOpen(String)
1377      * opened} unconditionally (even if the caller of this method is in the
1378      * same module as the resource). </p>
1379      *
1380      * @implSpec The default implementation will first search the parent class
1381      * loader for the resource; if the parent is {@code null} the path of the
1382      * class loader built into the virtual machine is searched. If not found,
1383      * this method will invoke {@link #findResource(String)} to find the resource.
1384      *
1385      * @apiNote Where several modules are defined to the same class loader,
1386      * and where more than one module contains a resource with the given name,
1387      * then the ordering that modules are searched is not specified and may be
1388      * very unpredictable.
1389      * When overriding this method it is recommended that an implementation
1390      * ensures that any delegation is consistent with the {@link
1391      * #getResources(java.lang.String) getResources(String)} method.
1392      *
1393      * @param  name
1394      *         The resource name
1395      *
1396      * @return  {@code URL} object for reading the resource; {@code null} if
1397      *          the resource could not be found, a {@code URL} could not be
1398      *          constructed to locate the resource, the resource is in a package
1399      *          that is not opened unconditionally, or access to the resource is
1400      *          denied by the security manager.
1401      *
1402      * @throws  NullPointerException If {@code name} is {@code null}
1403      *
1404      * @since  1.1
1405      */
1406     public URL getResource(String name) {
1407         Objects.requireNonNull(name);
1408         URL url;
1409         if (parent != null) {
1410             url = parent.getResource(name);
1411         } else {
1412             url = BootLoader.findResource(name);
1413         }
1414         if (url == null) {
1415             url = findResource(name);
1416         }
1417         return url;
1418     }
1419 
1420     /**
1421      * Finds all the resources with the given name. A resource is some data
1422      * (images, audio, text, etc) that can be accessed by class code in a way
1423      * that is independent of the location of the code.
1424      *
1425      * <p> The name of a resource is a {@code /}-separated path name that
1426      * identifies the resource. </p>
1427      *
1428      * <p> Resources in named modules are subject to the encapsulation rules
1429      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1430      * Additionally, and except for the special case where the resource has a
1431      * name ending with "{@code .class}", this method will only find resources in
1432      * packages of named modules when the package is {@link Module#isOpen(String)
1433      * opened} unconditionally (even if the caller of this method is in the
1434      * same module as the resource). </p>
1435      *
1436      * @implSpec The default implementation will first search the parent class
1437      * loader for the resource; if the parent is {@code null} the path of the
1438      * class loader built into the virtual machine is searched. It then
1439      * invokes {@link #findResources(String)} to find the resources with the
1440      * name in this class loader. It returns an enumeration whose elements
1441      * are the URLs found by searching the parent class loader followed by
1442      * the elements found with {@code findResources}.
1443      *
1444      * @apiNote Where several modules are defined to the same class loader,
1445      * and where more than one module contains a resource with the given name,
1446      * then the ordering is not specified and may be very unpredictable.
1447      * When overriding this method it is recommended that an
1448      * implementation ensures that any delegation is consistent with the {@link
1449      * #getResource(java.lang.String) getResource(String)} method. This should
1450      * ensure that the first element returned by the Enumeration's
1451      * {@code nextElement} method is the same resource that the
1452      * {@code getResource(String)} method would return.
1453      *
1454      * @param  name
1455      *         The resource name
1456      *
1457      * @return  An enumeration of {@link java.net.URL URL} objects for the
1458      *          resource. If no resources could be found, the enumeration will
1459      *          be empty. Resources for which a {@code URL} cannot be
1460      *          constructed, are in a package that is not opened
1461      *          unconditionally, or access to the resource is denied by the
1462      *          security manager, are not returned in the enumeration.
1463      *
1464      * @throws  IOException
1465      *          If I/O errors occur
1466      * @throws  NullPointerException If {@code name} is {@code null}
1467      *
1468      * @since  1.2
1469      */
1470     public Enumeration<URL> getResources(String name) throws IOException {
1471         Objects.requireNonNull(name);
1472         @SuppressWarnings("unchecked")
1473         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1474         if (parent != null) {
1475             tmp[0] = parent.getResources(name);
1476         } else {
1477             tmp[0] = BootLoader.findResources(name);
1478         }
1479         tmp[1] = findResources(name);
1480 
1481         return new CompoundEnumeration<>(tmp);
1482     }
1483 
1484     /**
1485      * Returns a stream whose elements are the URLs of all the resources with
1486      * the given name. A resource is some data (images, audio, text, etc) that
1487      * can be accessed by class code in a way that is independent of the
1488      * location of the code.
1489      *
1490      * <p> The name of a resource is a {@code /}-separated path name that
1491      * identifies the resource.
1492      *
1493      * <p> The resources will be located when the returned stream is evaluated.
1494      * If the evaluation results in an {@code IOException} then the I/O
1495      * exception is wrapped in an {@link UncheckedIOException} that is then
1496      * thrown.
1497      *
1498      * <p> Resources in named modules are subject to the encapsulation rules
1499      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1500      * Additionally, and except for the special case where the resource has a
1501      * name ending with "{@code .class}", this method will only find resources in
1502      * packages of named modules when the package is {@link Module#isOpen(String)
1503      * opened} unconditionally (even if the caller of this method is in the
1504      * same module as the resource). </p>
1505      *
1506      * @implSpec The default implementation invokes {@link #getResources(String)
1507      * getResources} to find all the resources with the given name and returns
1508      * a stream with the elements in the enumeration as the source.
1509      *
1510      * @apiNote When overriding this method it is recommended that an
1511      * implementation ensures that any delegation is consistent with the {@link
1512      * #getResource(java.lang.String) getResource(String)} method. This should
1513      * ensure that the first element returned by the stream is the same
1514      * resource that the {@code getResource(String)} method would return.
1515      *
1516      * @param  name
1517      *         The resource name
1518      *
1519      * @return  A stream of resource {@link java.net.URL URL} objects. If no
1520      *          resources could  be found, the stream will be empty. Resources
1521      *          for which a {@code URL} cannot be constructed, are in a package
1522      *          that is not opened unconditionally, or access to the resource
1523      *          is denied by the security manager, will not be in the stream.
1524      *
1525      * @throws  NullPointerException If {@code name} is {@code null}
1526      *
1527      * @since  9
1528      */
1529     public Stream<URL> resources(String name) {
1530         Objects.requireNonNull(name);
1531         int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE;
1532         Supplier<Spliterator<URL>> si = () -> {
1533             try {
1534                 return Spliterators.spliteratorUnknownSize(
1535                     getResources(name).asIterator(), characteristics);
1536             } catch (IOException e) {
1537                 throw new UncheckedIOException(e);
1538             }
1539         };
1540         return StreamSupport.stream(si, characteristics, false);
1541     }
1542 
1543     /**
1544      * Finds the resource with the given name. Class loader implementations
1545      * should override this method.
1546      *
1547      * <p> For resources in named modules then the method must implement the
1548      * rules for encapsulation specified in the {@code Module} {@link
1549      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1550      * it must not find non-"{@code .class}" resources in packages of named
1551      * modules unless the package is {@link Module#isOpen(String) opened}
1552      * unconditionally. </p>
1553      *
1554      * @implSpec The default implementation returns {@code null}.
1555      *
1556      * @param  name
1557      *         The resource name
1558      *
1559      * @return  {@code URL} object for reading the resource; {@code null} if
1560      *          the resource could not be found, a {@code URL} could not be
1561      *          constructed to locate the resource, the resource is in a package
1562      *          that is not opened unconditionally, or access to the resource is
1563      *          denied by the security manager.
1564      *
1565      * @since  1.2
1566      */
1567     protected URL findResource(String name) {
1568         return null;
1569     }
1570 
1571     /**
1572      * Returns an enumeration of {@link java.net.URL URL} objects
1573      * representing all the resources with the given name. Class loader
1574      * implementations should override this method.
1575      *
1576      * <p> For resources in named modules then the method must implement the
1577      * rules for encapsulation specified in the {@code Module} {@link
1578      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1579      * it must not find non-"{@code .class}" resources in packages of named
1580      * modules unless the package is {@link Module#isOpen(String) opened}
1581      * unconditionally. </p>
1582      *
1583      * @implSpec The default implementation returns an enumeration that
1584      * contains no elements.
1585      *
1586      * @param  name
1587      *         The resource name
1588      *
1589      * @return  An enumeration of {@link java.net.URL URL} objects for
1590      *          the resource. If no resources could  be found, the enumeration
1591      *          will be empty. Resources for which a {@code URL} cannot be
1592      *          constructed, are in a package that is not opened unconditionally,
1593      *          or access to the resource is denied by the security manager,
1594      *          are not returned in the enumeration.
1595      *
1596      * @throws  IOException
1597      *          If I/O errors occur
1598      *
1599      * @since  1.2
1600      */
1601     protected Enumeration<URL> findResources(String name) throws IOException {
1602         return Collections.emptyEnumeration();
1603     }
1604 
1605     /**
1606      * Registers the caller as
1607      * {@linkplain #isRegisteredAsParallelCapable() parallel capable}.
1608      * The registration succeeds if and only if all of the following
1609      * conditions are met:
1610      * <ol>
1611      * <li> no instance of the caller has been created</li>
1612      * <li> all of the super classes (except class Object) of the caller are
1613      * registered as parallel capable</li>
1614      * </ol>
1615      * <p>Note that once a class loader is registered as parallel capable, there
1616      * is no way to change it back.</p>
1617      * <p>
1618      * In cases where this method is called from a context where the caller is
1619      * not a subclass of {@code ClassLoader} or there is no caller frame on the
1620      * stack (e.g. when called directly from a JNI attached thread),
1621      * {@code IllegalCallerException} is thrown.
1622      * </p>
1623      *
1624      * @return  {@code true} if the caller is successfully registered as
1625      *          parallel capable and {@code false} if otherwise.
1626      * @throws IllegalCallerException if the caller is not a subclass of {@code ClassLoader}
1627      *
1628      * @see #isRegisteredAsParallelCapable()
1629      *
1630      * @since   1.7
1631      */
1632     @CallerSensitive
1633     protected static boolean registerAsParallelCapable() {
1634         return registerAsParallelCapable(Reflection.getCallerClass());
1635     }
1636 
1637     // Caller-sensitive adapter method for reflective invocation
1638     @CallerSensitiveAdapter
1639     private static boolean registerAsParallelCapable(Class<?> caller) {
1640         if ((caller == null) || !ClassLoader.class.isAssignableFrom(caller)) {
1641             throw new IllegalCallerException(caller + " not a subclass of ClassLoader");
1642         }
1643         return ParallelLoaders.register(caller.asSubclass(ClassLoader.class));
1644     }
1645 
1646     /**
1647      * Returns {@code true} if this class loader is registered as
1648      * {@linkplain #registerAsParallelCapable parallel capable}, otherwise
1649      * {@code false}.
1650      *
1651      * @return  {@code true} if this class loader is parallel capable,
1652      *          otherwise {@code false}.
1653      *
1654      * @see #registerAsParallelCapable()
1655      *
1656      * @since   9
1657      */
1658     public final boolean isRegisteredAsParallelCapable() {
1659         return ParallelLoaders.isRegistered(this.getClass());
1660     }
1661 
1662     /**
1663      * Find a resource of the specified name from the search path used to load
1664      * classes.  This method locates the resource through the system class
1665      * loader (see {@link #getSystemClassLoader()}).
1666      *
1667      * <p> Resources in named modules are subject to the encapsulation rules
1668      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1669      * Additionally, and except for the special case where the resource has a
1670      * name ending with "{@code .class}", this method will only find resources in
1671      * packages of named modules when the package is {@link Module#isOpen(String)
1672      * opened} unconditionally. </p>
1673      *
1674      * @param  name
1675      *         The resource name
1676      *
1677      * @return  A {@link java.net.URL URL} to the resource; {@code
1678      *          null} if the resource could not be found, a URL could not be
1679      *          constructed to locate the resource, the resource is in a package
1680      *          that is not opened unconditionally or access to the resource is
1681      *          denied by the security manager.
1682      *
1683      * @since  1.1
1684      */
1685     public static URL getSystemResource(String name) {
1686         return getSystemClassLoader().getResource(name);
1687     }
1688 
1689     /**
1690      * Finds all resources of the specified name from the search path used to
1691      * load classes.  The resources thus found are returned as an
1692      * {@link java.util.Enumeration Enumeration} of {@link
1693      * java.net.URL URL} objects.
1694      *
1695      * <p> The search order is described in the documentation for {@link
1696      * #getSystemResource(String)}.  </p>
1697      *
1698      * <p> Resources in named modules are subject to the encapsulation rules
1699      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1700      * Additionally, and except for the special case where the resource has a
1701      * name ending with "{@code .class}", this method will only find resources in
1702      * packages of named modules when the package is {@link Module#isOpen(String)
1703      * opened} unconditionally. </p>
1704      *
1705      * @param  name
1706      *         The resource name
1707      *
1708      * @return  An enumeration of {@link java.net.URL URL} objects for
1709      *          the resource. If no resources could  be found, the enumeration
1710      *          will be empty. Resources for which a {@code URL} cannot be
1711      *          constructed, are in a package that is not opened unconditionally,
1712      *          or access to the resource is denied by the security manager,
1713      *          are not returned in the enumeration.
1714      *
1715      * @throws  IOException
1716      *          If I/O errors occur
1717      *
1718      * @since  1.2
1719      */
1720     public static Enumeration<URL> getSystemResources(String name)
1721         throws IOException
1722     {
1723         return getSystemClassLoader().getResources(name);
1724     }
1725 
1726     /**
1727      * Returns an input stream for reading the specified resource.
1728      *
1729      * <p> The search order is described in the documentation for {@link
1730      * #getResource(String)}.  </p>
1731      *
1732      * <p> Resources in named modules are subject to the encapsulation rules
1733      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1734      * Additionally, and except for the special case where the resource has a
1735      * name ending with "{@code .class}", this method will only find resources in
1736      * packages of named modules when the package is {@link Module#isOpen(String)
1737      * opened} unconditionally. </p>
1738      *
1739      * @param  name
1740      *         The resource name
1741      *
1742      * @return  An input stream for reading the resource; {@code null} if the
1743      *          resource could not be found, the resource is in a package that
1744      *          is not opened unconditionally, or access to the resource is
1745      *          denied by the security manager.
1746      *
1747      * @throws  NullPointerException If {@code name} is {@code null}
1748      *
1749      * @since  1.1
1750      */
1751     public InputStream getResourceAsStream(String name) {
1752         Objects.requireNonNull(name);
1753         URL url = getResource(name);
1754         try {
1755             return url != null ? url.openStream() : null;
1756         } catch (IOException e) {
1757             return null;
1758         }
1759     }
1760 
1761     /**
1762      * Open for reading, a resource of the specified name from the search path
1763      * used to load classes.  This method locates the resource through the
1764      * system class loader (see {@link #getSystemClassLoader()}).
1765      *
1766      * <p> Resources in named modules are subject to the encapsulation rules
1767      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1768      * Additionally, and except for the special case where the resource has a
1769      * name ending with "{@code .class}", this method will only find resources in
1770      * packages of named modules when the package is {@link Module#isOpen(String)
1771      * opened} unconditionally. </p>
1772      *
1773      * @param  name
1774      *         The resource name
1775      *
1776      * @return  An input stream for reading the resource; {@code null} if the
1777      *          resource could not be found, the resource is in a package that
1778      *          is not opened unconditionally, or access to the resource is
1779      *          denied by the security manager.
1780      *
1781      * @since  1.1
1782      */
1783     public static InputStream getSystemResourceAsStream(String name) {
1784         URL url = getSystemResource(name);
1785         try {
1786             return url != null ? url.openStream() : null;
1787         } catch (IOException e) {
1788             return null;
1789         }
1790     }
1791 
1792 
1793     // -- Hierarchy --
1794 
1795     /**
1796      * Returns the parent class loader for delegation. Some implementations may
1797      * use {@code null} to represent the bootstrap class loader. This method
1798      * will return {@code null} in such implementations if this class loader's
1799      * parent is the bootstrap class loader.
1800      *
1801      * @return  The parent {@code ClassLoader}
1802      *
1803      * @throws  SecurityException
1804      *          If a security manager is present, and the caller's class loader
1805      *          is not {@code null} and is not an ancestor of this class loader,
1806      *          and the caller does not have the
1807      *          {@link RuntimePermission}{@code ("getClassLoader")}
1808      *
1809      * @since  1.2
1810      */
1811     @CallerSensitive
1812     public final ClassLoader getParent() {
1813         if (parent == null)
1814             return null;
1815         @SuppressWarnings("removal")
1816         SecurityManager sm = System.getSecurityManager();
1817         if (sm != null) {
1818             // Check access to the parent class loader
1819             // If the caller's class loader is same as this class loader,
1820             // permission check is performed.
1821             checkClassLoaderPermission(parent, Reflection.getCallerClass());
1822         }
1823         return parent;
1824     }
1825 
1826     /**
1827      * Returns the unnamed {@code Module} for this class loader.
1828      *
1829      * @return The unnamed Module for this class loader
1830      *
1831      * @see Module#isNamed()
1832      * @since 9
1833      */
1834     public final Module getUnnamedModule() {
1835         return unnamedModule;
1836     }
1837 
1838     /**
1839      * Returns the platform class loader.  All
1840      * <a href="#builtinLoaders">platform classes</a> are visible to
1841      * the platform class loader.
1842      *
1843      * @implNote The name of the builtin platform class loader is
1844      * {@code "platform"}.
1845      *
1846      * @return  The platform {@code ClassLoader}.
1847      *
1848      * @throws  SecurityException
1849      *          If a security manager is present, and the caller's class loader is
1850      *          not {@code null}, and the caller's class loader is not the same
1851      *          as or an ancestor of the platform class loader,
1852      *          and the caller does not have the
1853      *          {@link RuntimePermission}{@code ("getClassLoader")}
1854      *
1855      * @since 9
1856      */
1857     @CallerSensitive
1858     public static ClassLoader getPlatformClassLoader() {
1859         @SuppressWarnings("removal")
1860         SecurityManager sm = System.getSecurityManager();
1861         ClassLoader loader = getBuiltinPlatformClassLoader();
1862         if (sm != null) {
1863             checkClassLoaderPermission(loader, Reflection.getCallerClass());
1864         }
1865         return loader;
1866     }
1867 
1868     /**
1869      * Returns the system class loader.  This is the default
1870      * delegation parent for new {@code ClassLoader} instances, and is
1871      * typically the class loader used to start the application.
1872      *
1873      * <p> This method is first invoked early in the runtime's startup
1874      * sequence, at which point it creates the system class loader. This
1875      * class loader will be the context class loader for the main application
1876      * thread (for example, the thread that invokes the {@code main} method of
1877      * the main class).
1878      *
1879      * <p> The default system class loader is an implementation-dependent
1880      * instance of this class.
1881      *
1882      * <p> If the system property "{@systemProperty java.system.class.loader}"
1883      * is defined when this method is first invoked then the value of that
1884      * property is taken to be the name of a class that will be returned as the
1885      * system class loader. The class is loaded using the default system class
1886      * loader and must define a public constructor that takes a single parameter
1887      * of type {@code ClassLoader} which is used as the delegation parent. An
1888      * instance is then created using this constructor with the default system
1889      * class loader as the parameter.  The resulting class loader is defined
1890      * to be the system class loader. During construction, the class loader
1891      * should take great care to avoid calling {@code getSystemClassLoader()}.
1892      * If circular initialization of the system class loader is detected then
1893      * an {@code IllegalStateException} is thrown.
1894      *
1895      * @implNote The system property to override the system class loader is not
1896      * examined until the VM is almost fully initialized. Code that executes
1897      * this method during startup should take care not to cache the return
1898      * value until the system is fully initialized.
1899      *
1900      * <p> The name of the built-in system class loader is {@code "app"}.
1901      * The system property "{@code java.class.path}" is read during early
1902      * initialization of the VM to determine the class path.
1903      * An empty value of "{@code java.class.path}" property is interpreted
1904      * differently depending on whether the initial module (the module
1905      * containing the main class) is named or unnamed:
1906      * If named, the built-in system class loader will have no class path and
1907      * will search for classes and resources using the application module path;
1908      * otherwise, if unnamed, it will set the class path to the current
1909      * working directory.
1910      *
1911      * <p> JAR files on the class path may contain a {@code Class-Path} manifest
1912      * attribute to specify dependent JAR files to be included in the class path.
1913      * {@code Class-Path} entries must meet certain conditions for validity (see
1914      * the <a href="{@docRoot}/../specs/jar/jar.html#class-path-attribute">
1915      * JAR File Specification</a> for details).  Invalid {@code Class-Path}
1916      * entries are ignored.  For debugging purposes, ignored entries can be
1917      * printed to the console if the
1918      * {@systemProperty jdk.net.URLClassPath.showIgnoredClassPathEntries} system
1919      * property is set to {@code true}.
1920      *
1921      * @return  The system {@code ClassLoader}
1922      *
1923      * @throws  SecurityException
1924      *          If a security manager is present, and the caller's class loader
1925      *          is not {@code null} and is not the same as or an ancestor of the
1926      *          system class loader, and the caller does not have the
1927      *          {@link RuntimePermission}{@code ("getClassLoader")}
1928      *
1929      * @throws  IllegalStateException
1930      *          If invoked recursively during the construction of the class
1931      *          loader specified by the "{@code java.system.class.loader}"
1932      *          property.
1933      *
1934      * @throws  Error
1935      *          If the system property "{@code java.system.class.loader}"
1936      *          is defined but the named class could not be loaded, the
1937      *          provider class does not define the required constructor, or an
1938      *          exception is thrown by that constructor when it is invoked. The
1939      *          underlying cause of the error can be retrieved via the
1940      *          {@link Throwable#getCause()} method.
1941      */
1942     @CallerSensitive
1943     public static ClassLoader getSystemClassLoader() {
1944         switch (VM.initLevel()) {
1945             case 0:
1946             case 1:
1947             case 2:
1948                 // the system class loader is the built-in app class loader during startup
1949                 return getBuiltinAppClassLoader();
1950             case 3:
1951                 String msg = "getSystemClassLoader cannot be called during the system class loader instantiation";
1952                 throw new IllegalStateException(msg);
1953             default:
1954                 // system fully initialized
1955                 assert VM.isBooted() && scl != null;
1956                 @SuppressWarnings("removal")
1957                 SecurityManager sm = System.getSecurityManager();
1958                 if (sm != null) {
1959                     checkClassLoaderPermission(scl, Reflection.getCallerClass());
1960                 }
1961                 return scl;
1962         }
1963     }
1964 
1965     static ClassLoader getBuiltinPlatformClassLoader() {
1966         return ClassLoaders.platformClassLoader();
1967     }
1968 
1969     static ClassLoader getBuiltinAppClassLoader() {
1970         return ClassLoaders.appClassLoader();
1971     }
1972 
1973     /*
1974      * Initialize the system class loader that may be a custom class on the
1975      * application class path or application module path.
1976      *
1977      * @see java.lang.System#initPhase3
1978      */
1979     static synchronized ClassLoader initSystemClassLoader() {
1980         if (VM.initLevel() != 3) {
1981             throw new InternalError("system class loader cannot be set at initLevel " +
1982                                     VM.initLevel());
1983         }
1984 
1985         // detect recursive initialization
1986         if (scl != null) {
1987             throw new IllegalStateException("recursive invocation");
1988         }
1989 
1990         ClassLoader builtinLoader = getBuiltinAppClassLoader();
1991 
1992         // All are privileged frames.  No need to call doPrivileged.
1993         String cn = System.getProperty("java.system.class.loader");
1994         if (cn != null) {
1995             try {
1996                 // custom class loader is only supported to be loaded from unnamed module
1997                 Constructor<?> ctor = Class.forName(cn, false, builtinLoader)
1998                                            .getDeclaredConstructor(ClassLoader.class);
1999                 scl = (ClassLoader) ctor.newInstance(builtinLoader);
2000             } catch (Exception e) {
2001                 Throwable cause = e;
2002                 if (e instanceof InvocationTargetException) {
2003                     cause = e.getCause();
2004                     if (cause instanceof Error) {
2005                         throw (Error) cause;
2006                     }
2007                 }
2008                 if (cause instanceof RuntimeException) {
2009                     throw (RuntimeException) cause;
2010                 }
2011                 throw new Error(cause.getMessage(), cause);
2012             }
2013         } else {
2014             scl = builtinLoader;
2015         }
2016         return scl;
2017     }
2018 
2019     // Returns true if the specified class loader can be found in this class
2020     // loader's delegation chain.
2021     boolean isAncestor(ClassLoader cl) {
2022         ClassLoader acl = this;
2023         do {
2024             acl = acl.parent;
2025             if (cl == acl) {
2026                 return true;
2027             }
2028         } while (acl != null);
2029         return false;
2030     }
2031 
2032     // Tests if class loader access requires "getClassLoader" permission
2033     // check.  A class loader 'from' can access class loader 'to' if
2034     // class loader 'from' is same as class loader 'to' or an ancestor
2035     // of 'to'.  The class loader in a system domain can access
2036     // any class loader.
2037     private static boolean needsClassLoaderPermissionCheck(ClassLoader from,
2038                                                            ClassLoader to)
2039     {
2040         if (from == to)
2041             return false;
2042 
2043         if (from == null)
2044             return false;
2045 
2046         return !to.isAncestor(from);
2047     }
2048 
2049     // Returns the class's class loader, or null if none.
2050     static ClassLoader getClassLoader(Class<?> caller) {
2051         // This can be null if the VM is requesting it
2052         if (caller == null) {
2053             return null;
2054         }
2055         // Circumvent security check since this is package-private
2056         return caller.getClassLoader0();
2057     }
2058 
2059     /*
2060      * Checks RuntimePermission("getClassLoader") permission
2061      * if caller's class loader is not null and caller's class loader
2062      * is not the same as or an ancestor of the given cl argument.
2063      */
2064     static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
2065         @SuppressWarnings("removal")
2066         SecurityManager sm = System.getSecurityManager();
2067         if (sm != null) {
2068             // caller can be null if the VM is requesting it
2069             ClassLoader ccl = getClassLoader(caller);
2070             if (needsClassLoaderPermissionCheck(ccl, cl)) {
2071                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
2072             }
2073         }
2074     }
2075 
2076     // The system class loader
2077     // @GuardedBy("ClassLoader.class")
2078     private static volatile ClassLoader scl;
2079 
2080     // -- Package --
2081 
2082     /**
2083      * Define a Package of the given Class object.
2084      *
2085      * If the given class represents an array type, a primitive type or void,
2086      * this method returns {@code null}.
2087      *
2088      * This method does not throw IllegalArgumentException.
2089      */
2090     Package definePackage(Class<?> c) {
2091         if (c.isPrimitive() || c.isArray()) {
2092             return null;
2093         }
2094 
2095         return definePackage(c.getPackageName(), c.getModule());
2096     }
2097 
2098     /**
2099      * Defines a Package of the given name and module
2100      *
2101      * This method does not throw IllegalArgumentException.
2102      *
2103      * @param name package name
2104      * @param m    module
2105      */
2106     Package definePackage(String name, Module m) {
2107         if (name.isEmpty() && m.isNamed()) {
2108             throw new InternalError("unnamed package in  " + m);
2109         }
2110 
2111         // check if Package object is already defined
2112         NamedPackage pkg = packages.get(name);
2113         if (pkg instanceof Package)
2114             return (Package)pkg;
2115 
2116         return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m));
2117     }
2118 
2119     /*
2120      * Returns a Package object for the named package
2121      */
2122     private Package toPackage(String name, NamedPackage p, Module m) {
2123         // define Package object if the named package is not yet defined
2124         if (p == null)
2125             return NamedPackage.toPackage(name, m);
2126 
2127         // otherwise, replace the NamedPackage object with Package object
2128         if (p instanceof Package)
2129             return (Package)p;
2130 
2131         return NamedPackage.toPackage(p.packageName(), p.module());
2132     }
2133 
2134     /**
2135      * Defines a package by <a href="#binary-name">name</a> in this {@code ClassLoader}.
2136      * <p>
2137      * <a href="#binary-name">Package names</a> must be unique within a class loader and
2138      * cannot be redefined or changed once created.
2139      * <p>
2140      * If a class loader wishes to define a package with specific properties,
2141      * such as version information, then the class loader should call this
2142      * {@code definePackage} method before calling {@code defineClass}.
2143      * Otherwise, the
2144      * {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass}
2145      * method will define a package in this class loader corresponding to the package
2146      * of the newly defined class; the properties of this defined package are
2147      * specified by {@link Package}.
2148      *
2149      * @apiNote
2150      * A class loader that wishes to define a package for classes in a JAR
2151      * typically uses the specification and implementation titles, versions, and
2152      * vendors from the JAR's manifest. If the package is specified as
2153      * {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest,
2154      * the {@code URL} of the JAR file is typically used as the {@code sealBase}.
2155      * If classes of package {@code 'p'} defined by this class loader
2156      * are loaded from multiple JARs, the {@code Package} object may contain
2157      * different information depending on the first class of package {@code 'p'}
2158      * defined and which JAR's manifest is read first to explicitly define
2159      * package {@code 'p'}.
2160      *
2161      * <p> It is strongly recommended that a class loader does not call this
2162      * method to explicitly define packages in <em>named modules</em>; instead,
2163      * the package will be automatically defined when a class is {@linkplain
2164      * #defineClass(String, byte[], int, int, ProtectionDomain) being defined}.
2165      * If it is desirable to define {@code Package} explicitly, it should ensure
2166      * that all packages in a named module are defined with the properties
2167      * specified by {@link Package}.  Otherwise, some {@code Package} objects
2168      * in a named module may be for example sealed with different seal base.
2169      *
2170      * @param  name
2171      *         The <a href="#binary-name">package name</a>
2172      *
2173      * @param  specTitle
2174      *         The specification title
2175      *
2176      * @param  specVersion
2177      *         The specification version
2178      *
2179      * @param  specVendor
2180      *         The specification vendor
2181      *
2182      * @param  implTitle
2183      *         The implementation title
2184      *
2185      * @param  implVersion
2186      *         The implementation version
2187      *
2188      * @param  implVendor
2189      *         The implementation vendor
2190      *
2191      * @param  sealBase
2192      *         If not {@code null}, then this package is sealed with
2193      *         respect to the given code source {@link java.net.URL URL}
2194      *         object.  Otherwise, the package is not sealed.
2195      *
2196      * @return  The newly defined {@code Package} object
2197      *
2198      * @throws  NullPointerException
2199      *          if {@code name} is {@code null}.
2200      *
2201      * @throws  IllegalArgumentException
2202      *          if a package of the given {@code name} is already
2203      *          defined by this class loader
2204      *
2205      *
2206      * @since  1.2
2207      *
2208      * @jvms 5.3 Creation and Loading
2209      * @see <a href="{@docRoot}/../specs/jar/jar.html#package-sealing">
2210      *      The JAR File Specification: Package Sealing</a>
2211      */
2212     protected Package definePackage(String name, String specTitle,
2213                                     String specVersion, String specVendor,
2214                                     String implTitle, String implVersion,
2215                                     String implVendor, URL sealBase)
2216     {
2217         Objects.requireNonNull(name);
2218 
2219         // definePackage is not final and may be overridden by custom class loader
2220         Package p = new Package(name, specTitle, specVersion, specVendor,
2221                                 implTitle, implVersion, implVendor,
2222                                 sealBase, this);
2223 
2224         if (packages.putIfAbsent(name, p) != null)
2225             throw new IllegalArgumentException(name);
2226 
2227         return p;
2228     }
2229 
2230     /**
2231      * Returns a {@code Package} of the given <a href="#binary-name">name</a> that
2232      * has been defined by this class loader.
2233      *
2234      * @param  name The <a href="#binary-name">package name</a>
2235      *
2236      * @return The {@code Package} of the given name that has been defined
2237      *         by this class loader, or {@code null} if not found
2238      *
2239      * @throws  NullPointerException
2240      *          if {@code name} is {@code null}.
2241      *
2242      * @jvms 5.3 Creation and Loading
2243      *
2244      * @since  9
2245      */
2246     public final Package getDefinedPackage(String name) {
2247         Objects.requireNonNull(name, "name cannot be null");
2248 
2249         NamedPackage p = packages.get(name);
2250         if (p == null)
2251             return null;
2252 
2253         return definePackage(name, p.module());
2254     }
2255 
2256     /**
2257      * Returns all of the {@code Package}s that have been defined by
2258      * this class loader.  The returned array has no duplicated {@code Package}s
2259      * of the same name.
2260      *
2261      * @apiNote This method returns an array rather than a {@code Set} or {@code Stream}
2262      *          for consistency with the existing {@link #getPackages} method.
2263      *
2264      * @return The array of {@code Package} objects that have been defined by
2265      *         this class loader; or a zero length array if no package has been
2266      *         defined by this class loader.
2267      *
2268      * @jvms 5.3 Creation and Loading
2269      *
2270      * @since  9
2271      */
2272     public final Package[] getDefinedPackages() {
2273         return packages().toArray(Package[]::new);
2274     }
2275 
2276     /**
2277      * Finds a package by <a href="#binary-name">name</a> in this class loader and its ancestors.
2278      * <p>
2279      * If this class loader defines a {@code Package} of the given name,
2280      * the {@code Package} is returned. Otherwise, the ancestors of
2281      * this class loader are searched recursively (parent by parent)
2282      * for a {@code Package} of the given name.
2283      *
2284      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2285      * may delegate to the application class loader but the application class
2286      * loader is not its ancestor.  When invoked on the platform class loader,
2287      * this method  will not find packages defined to the application
2288      * class loader.
2289      *
2290      * @param  name
2291      *         The <a href="#binary-name">package name</a>
2292      *
2293      * @return The {@code Package} of the given name that has been defined by
2294      *         this class loader or its ancestors, or {@code null} if not found.
2295      *
2296      * @throws  NullPointerException
2297      *          if {@code name} is {@code null}.
2298      *
2299      * @deprecated
2300      * If multiple class loaders delegate to each other and define classes
2301      * with the same package name, and one such loader relies on the lookup
2302      * behavior of {@code getPackage} to return a {@code Package} from
2303      * a parent loader, then the properties exposed by the {@code Package}
2304      * may not be as expected in the rest of the program.
2305      * For example, the {@code Package} will only expose annotations from the
2306      * {@code package-info.class} file defined by the parent loader, even if
2307      * annotations exist in a {@code package-info.class} file defined by
2308      * a child loader.  A more robust approach is to use the
2309      * {@link ClassLoader#getDefinedPackage} method which returns
2310      * a {@code Package} for the specified class loader.
2311      *
2312      * @see ClassLoader#getDefinedPackage(String)
2313      *
2314      * @since  1.2
2315      */
2316     @Deprecated(since="9")
2317     protected Package getPackage(String name) {
2318         Package pkg = getDefinedPackage(name);
2319         if (pkg == null) {
2320             if (parent != null) {
2321                 pkg = parent.getPackage(name);
2322             } else {
2323                 pkg = BootLoader.getDefinedPackage(name);
2324             }
2325         }
2326         return pkg;
2327     }
2328 
2329     /**
2330      * Returns all of the {@code Package}s that have been defined by
2331      * this class loader and its ancestors.  The returned array may contain
2332      * more than one {@code Package} object of the same package name, each
2333      * defined by a different class loader in the class loader hierarchy.
2334      *
2335      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2336      * may delegate to the application class loader. In other words,
2337      * packages in modules defined to the application class loader may be
2338      * visible to the platform class loader.  On the other hand,
2339      * the application class loader is not its ancestor and hence
2340      * when invoked on the platform class loader, this method will not
2341      * return any packages defined to the application class loader.
2342      *
2343      * @return  The array of {@code Package} objects that have been defined by
2344      *          this class loader and its ancestors
2345      *
2346      * @see ClassLoader#getDefinedPackages()
2347      *
2348      * @since  1.2
2349      */
2350     protected Package[] getPackages() {
2351         Stream<Package> pkgs = packages();
2352         ClassLoader ld = parent;
2353         while (ld != null) {
2354             pkgs = Stream.concat(ld.packages(), pkgs);
2355             ld = ld.parent;
2356         }
2357         return Stream.concat(BootLoader.packages(), pkgs)
2358                      .toArray(Package[]::new);
2359     }
2360 
2361 
2362 
2363     // package-private
2364 
2365     /**
2366      * Returns a stream of Packages defined in this class loader
2367      */
2368     Stream<Package> packages() {
2369         return packages.values().stream()
2370                        .map(p -> definePackage(p.packageName(), p.module()));
2371     }
2372 
2373     // -- Native library access --
2374 
2375     /**
2376      * Returns the absolute path name of a native library.  The VM invokes this
2377      * method to locate the native libraries that belong to classes loaded with
2378      * this class loader. If this method returns {@code null}, the VM
2379      * searches the library along the path specified as the
2380      * "{@code java.library.path}" property.
2381      *
2382      * @param  libname
2383      *         The library name
2384      *
2385      * @return  The absolute path of the native library
2386      *
2387      * @see  System#loadLibrary(String)
2388      * @see  System#mapLibraryName(String)
2389      *
2390      * @since  1.2
2391      */
2392     protected String findLibrary(String libname) {
2393         return null;
2394     }
2395 
2396     private final NativeLibraries libraries = NativeLibraries.newInstance(this);
2397 
2398     // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
2399     static NativeLibrary loadLibrary(Class<?> fromClass, File file) {
2400         ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();
2401         NativeLibraries libs = loader != null ? loader.libraries : BootLoader.getNativeLibraries();
2402         NativeLibrary nl = libs.loadLibrary(fromClass, file);
2403         if (nl != null) {
2404             return nl;
2405         }
2406         throw new UnsatisfiedLinkError("Can't load library: " + file);
2407     }
2408     static NativeLibrary loadLibrary(Class<?> fromClass, String name) {
2409         ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();
2410         if (loader == null) {
2411             NativeLibrary nl = BootLoader.getNativeLibraries().loadLibrary(fromClass, name);
2412             if (nl != null) {
2413                 return nl;
2414             }
2415             throw new UnsatisfiedLinkError("no " + name +
2416                     " in system library path: " + StaticProperty.sunBootLibraryPath());
2417         }
2418 
2419         NativeLibraries libs = loader.libraries;
2420         // First load from the file returned from ClassLoader::findLibrary, if found.
2421         String libfilename = loader.findLibrary(name);
2422         if (libfilename != null) {
2423             File libfile = new File(libfilename);
2424             if (!libfile.isAbsolute()) {
2425                 throw new UnsatisfiedLinkError(
2426                         "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);
2427             }
2428             NativeLibrary nl = libs.loadLibrary(fromClass, libfile);
2429             if (nl != null) {
2430                 return nl;
2431             }
2432             throw new UnsatisfiedLinkError("Can't load " + libfilename);
2433         }
2434         // Then load from system library path and java library path
2435         NativeLibrary nl = libs.loadLibrary(fromClass, name);
2436         if (nl != null) {
2437             return nl;
2438         }
2439 
2440         // Oops, it failed
2441         throw new UnsatisfiedLinkError("no " + name +
2442                 " in java.library.path: " + StaticProperty.javaLibraryPath());
2443     }
2444 
2445     /*
2446      * Invoked in the VM class linking code.
2447      */
2448     static long findNative(ClassLoader loader, String entryName) {
2449         if (loader == null) {
2450             return BootLoader.getNativeLibraries().find(entryName);
2451         } else {
2452             return loader.libraries.find(entryName);
2453         }
2454     }
2455 
2456     // -- Assertion management --
2457 
2458     final Object assertionLock;
2459 
2460     // The default toggle for assertion checking.
2461     // @GuardedBy("assertionLock")
2462     private boolean defaultAssertionStatus = false;
2463 
2464     // Maps String packageName to Boolean package default assertion status Note
2465     // that the default package is placed under a null map key.  If this field
2466     // is null then we are delegating assertion status queries to the VM, i.e.,
2467     // none of this ClassLoader's assertion status modification methods have
2468     // been invoked.
2469     // @GuardedBy("assertionLock")
2470     private Map<String, Boolean> packageAssertionStatus = null;
2471 
2472     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
2473     // field is null then we are delegating assertion status queries to the VM,
2474     // i.e., none of this ClassLoader's assertion status modification methods
2475     // have been invoked.
2476     // @GuardedBy("assertionLock")
2477     Map<String, Boolean> classAssertionStatus = null;
2478 
2479     /**
2480      * Sets the default assertion status for this class loader.  This setting
2481      * determines whether classes loaded by this class loader and initialized
2482      * in the future will have assertions enabled or disabled by default.
2483      * This setting may be overridden on a per-package or per-class basis by
2484      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
2485      * #setClassAssertionStatus(String, boolean)}.
2486      *
2487      * @param  enabled
2488      *         {@code true} if classes loaded by this class loader will
2489      *         henceforth have assertions enabled by default, {@code false}
2490      *         if they will have assertions disabled by default.
2491      *
2492      * @since  1.4
2493      */
2494     public void setDefaultAssertionStatus(boolean enabled) {
2495         synchronized (assertionLock) {
2496             if (classAssertionStatus == null)
2497                 initializeJavaAssertionMaps();
2498 
2499             defaultAssertionStatus = enabled;
2500         }
2501     }
2502 
2503     /**
2504      * Sets the package default assertion status for the named package.  The
2505      * package default assertion status determines the assertion status for
2506      * classes initialized in the future that belong to the named package or
2507      * any of its "subpackages".
2508      *
2509      * <p> A subpackage of a package named p is any package whose name begins
2510      * with "{@code p.}".  For example, {@code javax.swing.text} is a
2511      * subpackage of {@code javax.swing}, and both {@code java.util} and
2512      * {@code java.lang.reflect} are subpackages of {@code java}.
2513      *
2514      * <p> In the event that multiple package defaults apply to a given class,
2515      * the package default pertaining to the most specific package takes
2516      * precedence over the others.  For example, if {@code javax.lang} and
2517      * {@code javax.lang.reflect} both have package defaults associated with
2518      * them, the latter package default applies to classes in
2519      * {@code javax.lang.reflect}.
2520      *
2521      * <p> Package defaults take precedence over the class loader's default
2522      * assertion status, and may be overridden on a per-class basis by invoking
2523      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
2524      *
2525      * @param  packageName
2526      *         The name of the package whose package default assertion status
2527      *         is to be set. A {@code null} value indicates the unnamed
2528      *         package that is "current"
2529      *         (see section {@jls 7.4.2} of
2530      *         <cite>The Java Language Specification</cite>.)
2531      *
2532      * @param  enabled
2533      *         {@code true} if classes loaded by this classloader and
2534      *         belonging to the named package or any of its subpackages will
2535      *         have assertions enabled by default, {@code false} if they will
2536      *         have assertions disabled by default.
2537      *
2538      * @since  1.4
2539      */
2540     public void setPackageAssertionStatus(String packageName,
2541                                           boolean enabled) {
2542         synchronized (assertionLock) {
2543             if (packageAssertionStatus == null)
2544                 initializeJavaAssertionMaps();
2545 
2546             packageAssertionStatus.put(packageName, enabled);
2547         }
2548     }
2549 
2550     /**
2551      * Sets the desired assertion status for the named top-level class in this
2552      * class loader and any nested classes contained therein.  This setting
2553      * takes precedence over the class loader's default assertion status, and
2554      * over any applicable per-package default.  This method has no effect if
2555      * the named class has already been initialized.  (Once a class is
2556      * initialized, its assertion status cannot change.)
2557      *
2558      * <p> If the named class is not a top-level class, this invocation will
2559      * have no effect on the actual assertion status of any class. </p>
2560      *
2561      * @param  className
2562      *         The fully qualified class name of the top-level class whose
2563      *         assertion status is to be set.
2564      *
2565      * @param  enabled
2566      *         {@code true} if the named class is to have assertions
2567      *         enabled when (and if) it is initialized, {@code false} if the
2568      *         class is to have assertions disabled.
2569      *
2570      * @since  1.4
2571      */
2572     public void setClassAssertionStatus(String className, boolean enabled) {
2573         synchronized (assertionLock) {
2574             if (classAssertionStatus == null)
2575                 initializeJavaAssertionMaps();
2576 
2577             classAssertionStatus.put(className, enabled);
2578         }
2579     }
2580 
2581     /**
2582      * Sets the default assertion status for this class loader to
2583      * {@code false} and discards any package defaults or class assertion
2584      * status settings associated with the class loader.  This method is
2585      * provided so that class loaders can be made to ignore any command line or
2586      * persistent assertion status settings and "start with a clean slate."
2587      *
2588      * @since  1.4
2589      */
2590     public void clearAssertionStatus() {
2591         /*
2592          * Whether or not "Java assertion maps" are initialized, set
2593          * them to empty maps, effectively ignoring any present settings.
2594          */
2595         synchronized (assertionLock) {
2596             classAssertionStatus = new HashMap<>();
2597             packageAssertionStatus = new HashMap<>();
2598             defaultAssertionStatus = false;
2599         }
2600     }
2601 
2602     /**
2603      * Returns the assertion status that would be assigned to the specified
2604      * class if it were to be initialized at the time this method is invoked.
2605      * If the named class has had its assertion status set, the most recent
2606      * setting will be returned; otherwise, if any package default assertion
2607      * status pertains to this class, the most recent setting for the most
2608      * specific pertinent package default assertion status is returned;
2609      * otherwise, this class loader's default assertion status is returned.
2610      * </p>
2611      *
2612      * @param  className
2613      *         The fully qualified class name of the class whose desired
2614      *         assertion status is being queried.
2615      *
2616      * @return  The desired assertion status of the specified class.
2617      *
2618      * @see  #setClassAssertionStatus(String, boolean)
2619      * @see  #setPackageAssertionStatus(String, boolean)
2620      * @see  #setDefaultAssertionStatus(boolean)
2621      *
2622      * @since  1.4
2623      */
2624     boolean desiredAssertionStatus(String className) {
2625         synchronized (assertionLock) {
2626             // assert classAssertionStatus   != null;
2627             // assert packageAssertionStatus != null;
2628 
2629             // Check for a class entry
2630             Boolean result = classAssertionStatus.get(className);
2631             if (result != null)
2632                 return result.booleanValue();
2633 
2634             // Check for most specific package entry
2635             int dotIndex = className.lastIndexOf('.');
2636             if (dotIndex < 0) { // default package
2637                 result = packageAssertionStatus.get(null);
2638                 if (result != null)
2639                     return result.booleanValue();
2640             }
2641             while(dotIndex > 0) {
2642                 className = className.substring(0, dotIndex);
2643                 result = packageAssertionStatus.get(className);
2644                 if (result != null)
2645                     return result.booleanValue();
2646                 dotIndex = className.lastIndexOf('.', dotIndex-1);
2647             }
2648 
2649             // Return the classloader default
2650             return defaultAssertionStatus;
2651         }
2652     }
2653 
2654     // Set up the assertions with information provided by the VM.
2655     // Note: Should only be called inside a synchronized block
2656     private void initializeJavaAssertionMaps() {
2657         // assert Thread.holdsLock(assertionLock);
2658 
2659         classAssertionStatus = new HashMap<>();
2660         packageAssertionStatus = new HashMap<>();
2661         AssertionStatusDirectives directives = retrieveDirectives();
2662 
2663         for(int i = 0; i < directives.classes.length; i++)
2664             classAssertionStatus.put(directives.classes[i],
2665                                      directives.classEnabled[i]);
2666 
2667         for(int i = 0; i < directives.packages.length; i++)
2668             packageAssertionStatus.put(directives.packages[i],
2669                                        directives.packageEnabled[i]);
2670 
2671         defaultAssertionStatus = directives.deflt;
2672     }
2673 
2674     // Retrieves the assertion directives from the VM.
2675     private static native AssertionStatusDirectives retrieveDirectives();
2676 
2677 
2678     // -- Misc --
2679 
2680     /**
2681      * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
2682      * associated with this ClassLoader, creating it if it doesn't already exist.
2683      */
2684     ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() {
2685         ConcurrentHashMap<?, ?> map = classLoaderValueMap;
2686         if (map == null) {
2687             map = new ConcurrentHashMap<>();
2688             boolean set = trySetObjectField("classLoaderValueMap", map);
2689             if (!set) {
2690                 // beaten by someone else
2691                 map = classLoaderValueMap;
2692             }
2693         }
2694         return map;
2695     }
2696 
2697     // the storage for ClassLoaderValue(s) associated with this ClassLoader
2698     private volatile ConcurrentHashMap<?, ?> classLoaderValueMap;
2699 
2700     /**
2701      * Attempts to atomically set a volatile field in this object. Returns
2702      * {@code true} if not beaten by another thread. Avoids the use of
2703      * AtomicReferenceFieldUpdater in this class.
2704      */
2705     private boolean trySetObjectField(String name, Object obj) {
2706         Unsafe unsafe = Unsafe.getUnsafe();
2707         Class<?> k = ClassLoader.class;
2708         long offset;
2709         offset = unsafe.objectFieldOffset(k, name);
2710         return unsafe.compareAndSetReference(this, offset, null, obj);
2711     }
2712 
2713     /**
2714      * Called by the VM, during -Xshare:dump
2715      */
2716     private void resetArchivedStates() {
2717         if (parallelLockMap != null) {
2718             parallelLockMap.clear();
2719         }
2720         packages.clear();
2721         package2certs.clear();
2722         classes.clear();
2723         classLoaderValueMap = null;
2724     }
2725 }
2726 
2727 /*
2728  * A utility class that will enumerate over an array of enumerations.
2729  */
2730 final class CompoundEnumeration<E> implements Enumeration<E> {
2731     private final Enumeration<E>[] enums;
2732     private int index;
2733 
2734     public CompoundEnumeration(Enumeration<E>[] enums) {
2735         this.enums = enums;
2736     }
2737 
2738     private boolean next() {
2739         while (index < enums.length) {
2740             if (enums[index] != null && enums[index].hasMoreElements()) {
2741                 return true;
2742             }
2743             index++;
2744         }
2745         return false;
2746     }
2747 
2748     public boolean hasMoreElements() {
2749         return next();
2750     }
2751 
2752     public E nextElement() {
2753         if (!next()) {
2754             throw new NoSuchElementException();
2755         }
2756         return enums[index].nextElement();
2757     }
2758 }