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