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