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