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