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 
 738      * @param  name
 739      *         The <a href="#binary-name">binary name</a> of the class
 740      *
 741      * @return The resulting {@code Class} object, or {@code null}
 742      *         if the class could not be found.
 743      *
 744      * @since 9
 745      * @spec JPMS
 746      */
 747     protected Class<?> findClass(String moduleName, String name) {
 748         if (moduleName == null) {
 749             try {
 750                 return findClass(name);
 751             } catch (ClassNotFoundException ignore) { }
 752         }
 753         return null;
 754     }
 755 
 756 
 757     /**
 758      * Converts an array of bytes into an instance of class {@code Class}.
 759      * Before the {@code Class} can be used it must be resolved.  This method
 760      * is deprecated in favor of the version that takes a <a
 761      * href="#binary-name">binary name</a> as its first argument, and is more secure.
 762      *
 763      * @param  b
 764      *         The bytes that make up the class data.  The bytes in positions
 765      *         {@code off} through {@code off+len-1} should have the format
 766      *         of a valid class file as defined by
 767      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 768      *
 769      * @param  off
 770      *         The start offset in {@code b} of the class data
 771      *
 772      * @param  len
 773      *         The length of the class data
 774      *
 775      * @return  The {@code Class} object that was created from the specified
 776      *          class data
 777      *
 778      * @throws  ClassFormatError
 779      *          If the data did not contain a valid class
 780      *
 781      * @throws  IndexOutOfBoundsException
 782      *          If either {@code off} or {@code len} is negative, or if
 783      *          {@code off+len} is greater than {@code b.length}.
 784      *
 785      * @throws  SecurityException
 786      *          If an attempt is made to add this class to a package that
 787      *          contains classes that were signed by a different set of
 788      *          certificates than this class, or if an attempt is made
 789      *          to define a class in a package with a fully-qualified name
 790      *          that starts with "{@code java.}".
 791      *
 792      * @see  #loadClass(String, boolean)
 793      * @see  #resolveClass(Class)
 794      *
 795      * @deprecated  Replaced by {@link #defineClass(String, byte[], int, int)
 796      * defineClass(String, byte[], int, int)}
 797      */
 798     @Deprecated(since="1.1")
 799     protected final Class<?> defineClass(byte[] b, int off, int len)
 800         throws ClassFormatError
 801     {
 802         return defineClass(null, b, off, len, null);
 803     }
 804 
 805     /**
 806      * Converts an array of bytes into an instance of class {@code Class}.
 807      * Before the {@code Class} can be used it must be resolved.
 808      *
 809      * <p> This method assigns a default {@link java.security.ProtectionDomain
 810      * ProtectionDomain} to the newly defined class.  The
 811      * {@code ProtectionDomain} is effectively granted the same set of
 812      * permissions returned when {@link
 813      * java.security.Policy#getPermissions(java.security.CodeSource)
 814      * Policy.getPolicy().getPermissions(new CodeSource(null, null))}
 815      * is invoked.  The default protection domain is created on the first invocation
 816      * of {@link #defineClass(String, byte[], int, int) defineClass},
 817      * and re-used on subsequent invocations.
 818      *
 819      * <p> To assign a specific {@code ProtectionDomain} to the class, use
 820      * the {@link #defineClass(String, byte[], int, int,
 821      * java.security.ProtectionDomain) defineClass} method that takes a
 822      * {@code ProtectionDomain} as one of its arguments.  </p>
 823      *
 824      * <p>
 825      * This method defines a package in this class loader corresponding to the
 826      * package of the {@code Class} (if such a package has not already been defined
 827      * in this class loader). The name of the defined package is derived from
 828      * the <a href="#binary-name">binary name</a> of the class specified by
 829      * the byte array {@code b}.
 830      * Other properties of the defined package are as specified by {@link Package}.
 831      *
 832      * @param  name
 833      *         The expected <a href="#binary-name">binary name</a> of the class, or
 834      *         {@code null} if not known
 835      *
 836      * @param  b
 837      *         The bytes that make up the class data.  The bytes in positions
 838      *         {@code off} through {@code off+len-1} should have the format
 839      *         of a valid class file as defined by
 840      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 841      *
 842      * @param  off
 843      *         The start offset in {@code b} of the class data
 844      *
 845      * @param  len
 846      *         The length of the class data
 847      *
 848      * @return  The {@code Class} object that was created from the specified
 849      *          class data.
 850      *
 851      * @throws  ClassFormatError
 852      *          If the data did not contain a valid class
 853      *
 854      * @throws  IndexOutOfBoundsException
 855      *          If either {@code off} or {@code len} is negative, or if
 856      *          {@code off+len} is greater than {@code b.length}.
 857      *
 858      * @throws  SecurityException
 859      *          If an attempt is made to add this class to a package that
 860      *          contains classes that were signed by a different set of
 861      *          certificates than this class (which is unsigned), or if
 862      *          {@code name} begins with "{@code java.}".
 863      *
 864      * @see  #loadClass(String, boolean)
 865      * @see  #resolveClass(Class)
 866      * @see  java.security.CodeSource
 867      * @see  java.security.SecureClassLoader
 868      *
 869      * @since  1.1
 870      * @revised 9
 871      * @spec JPMS
 872      */
 873     protected final Class<?> defineClass(String name, byte[] b, int off, int len)
 874         throws ClassFormatError
 875     {
 876         return defineClass(name, b, off, len, null);
 877     }
 878 
 879     /* Determine protection domain, and check that:
 880         - not define java.* class,
 881         - signer of this class matches signers for the rest of the classes in
 882           package.
 883     */
 884     private ProtectionDomain preDefineClass(String name,
 885                                             ProtectionDomain pd)
 886     {
 887         if (!checkName(name))
 888             throw new NoClassDefFoundError("IllegalName: " + name);
 889 
 890         // Note:  Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
 891         // relies on the fact that spoofing is impossible if a class has a name
 892         // of the form "java.*"
 893         if ((name != null) && name.startsWith("java.")
 894                 && this != getBuiltinPlatformClassLoader()) {
 895             throw new SecurityException
 896                 ("Prohibited package name: " +
 897                  name.substring(0, name.lastIndexOf('.')));
 898         }
 899         if (pd == null) {
 900             pd = defaultDomain;
 901         }
 902 
 903         if (name != null) {
 904             checkCerts(name, pd.getCodeSource());
 905         }
 906 
 907         return pd;
 908     }
 909 
 910     private String defineClassSourceLocation(ProtectionDomain pd) {
 911         CodeSource cs = pd.getCodeSource();
 912         String source = null;
 913         if (cs != null && cs.getLocation() != null) {
 914             source = cs.getLocation().toString();
 915         }
 916         return source;
 917     }
 918 
 919     private void postDefineClass(Class<?> c, ProtectionDomain pd) {
 920         // define a named package, if not present
 921         getNamedPackage(c.getPackageName(), c.getModule());
 922 
 923         if (pd.getCodeSource() != null) {
 924             Certificate certs[] = pd.getCodeSource().getCertificates();
 925             if (certs != null)
 926                 setSigners(c, certs);
 927         }
 928     }
 929 
 930     /**
 931      * Converts an array of bytes into an instance of class {@code Class},
 932      * with a given {@code ProtectionDomain}.
 933      *
 934      * <p> If the given {@code ProtectionDomain} is {@code null},
 935      * then a default protection domain will be assigned to the class as specified
 936      * in the documentation for {@link #defineClass(String, byte[], int, int)}.
 937      * Before the class can be used it must be resolved.
 938      *
 939      * <p> The first class defined in a package determines the exact set of
 940      * certificates that all subsequent classes defined in that package must
 941      * contain.  The set of certificates for a class is obtained from the
 942      * {@link java.security.CodeSource CodeSource} within the
 943      * {@code ProtectionDomain} of the class.  Any classes added to that
 944      * package must contain the same set of certificates or a
 945      * {@code SecurityException} will be thrown.  Note that if
 946      * {@code name} is {@code null}, this check is not performed.
 947      * You should always pass in the <a href="#binary-name">binary name</a> of the
 948      * class you are defining as well as the bytes.  This ensures that the
 949      * class you are defining is indeed the class you think it is.
 950      *
 951      * <p> If the specified {@code name} begins with "{@code java.}", it can
 952      * only be defined by the {@linkplain #getPlatformClassLoader()
 953      * platform class loader} or its ancestors; otherwise {@code SecurityException}
 954      * will be thrown.  If {@code name} is not {@code null}, it must be equal to
 955      * the <a href="#binary-name">binary name</a> of the class
 956      * specified by the byte array {@code b}, otherwise a {@link
 957      * NoClassDefFoundError NoClassDefFoundError} will be thrown.
 958      *
 959      * <p> This method defines a package in this class loader corresponding to the
 960      * package of the {@code Class} (if such a package has not already been defined
 961      * in this class loader). The name of the defined package is derived from
 962      * the <a href="#binary-name">binary name</a> of the class specified by
 963      * the byte array {@code b}.
 964      * Other properties of the defined package are as specified by {@link Package}.
 965      *
 966      * @param  name
 967      *         The expected <a href="#binary-name">binary name</a> of the class, or
 968      *         {@code null} if not known
 969      *
 970      * @param  b
 971      *         The bytes that make up the class data. The bytes in positions
 972      *         {@code off} through {@code off+len-1} should have the format
 973      *         of a valid class file as defined by
 974      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
 975      *
 976      * @param  off
 977      *         The start offset in {@code b} of the class data
 978      *
 979      * @param  len
 980      *         The length of the class data
 981      *
 982      * @param  protectionDomain
 983      *         The {@code ProtectionDomain} of the class
 984      *
 985      * @return  The {@code Class} object created from the data,
 986      *          and {@code ProtectionDomain}.
 987      *
 988      * @throws  ClassFormatError
 989      *          If the data did not contain a valid class
 990      *
 991      * @throws  NoClassDefFoundError
 992      *          If {@code name} is not {@code null} and not equal to the
 993      *          <a href="#binary-name">binary name</a> of the class specified by {@code b}
 994      *
 995      * @throws  IndexOutOfBoundsException
 996      *          If either {@code off} or {@code len} is negative, or if
 997      *          {@code off+len} is greater than {@code b.length}.
 998      *
 999      * @throws  SecurityException
1000      *          If an attempt is made to add this class to a package that
1001      *          contains classes that were signed by a different set of
1002      *          certificates than this class, or if {@code name} begins with
1003      *          "{@code java.}" and this class loader is not the platform
1004      *          class loader or its ancestor.
1005      *
1006      * @revised 9
1007      * @spec JPMS
1008      */
1009     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
1010                                          ProtectionDomain protectionDomain)
1011         throws ClassFormatError
1012     {
1013         protectionDomain = preDefineClass(name, protectionDomain);
1014         String source = defineClassSourceLocation(protectionDomain);
1015         Class<?> c = defineClass1(this, name, b, off, len, protectionDomain, source);
1016         postDefineClass(c, protectionDomain);
1017         return c;
1018     }
1019 
1020     /**
1021      * Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
1022      * of class {@code Class}, with the given {@code ProtectionDomain}.
1023      * If the given {@code ProtectionDomain} is {@code null}, then a default
1024      * protection domain will be assigned to the class as
1025      * specified in the documentation for {@link #defineClass(String, byte[],
1026      * int, int)}.  Before the class can be used it must be resolved.
1027      *
1028      * <p>The rules about the first class defined in a package determining the
1029      * set of certificates for the package, the restrictions on class names,
1030      * and the defined package of the class
1031      * are identical to those specified in the documentation for {@link
1032      * #defineClass(String, byte[], int, int, ProtectionDomain)}.
1033      *
1034      * <p> An invocation of this method of the form
1035      * <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,}
1036      * <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same
1037      * result as the statements
1038      *
1039      *<p> <code>
1040      * ...<br>
1041      * byte[] temp = new byte[bBuffer.{@link
1042      * java.nio.ByteBuffer#remaining remaining}()];<br>
1043      *     bBuffer.{@link java.nio.ByteBuffer#get(byte[])
1044      * get}(temp);<br>
1045      *     return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
1046      * cl.defineClass}(name, temp, 0,
1047      * temp.length, pd);<br>
1048      * </code></p>
1049      *
1050      * @param  name
1051      *         The expected <a href="#binary-name">binary name</a>. of the class, or
1052      *         {@code null} if not known
1053      *
1054      * @param  b
1055      *         The bytes that make up the class data. The bytes from positions
1056      *         {@code b.position()} through {@code b.position() + b.limit() -1
1057      *         } should have the format of a valid class file as defined by
1058      *         <cite>The Java&trade; Virtual Machine Specification</cite>.
1059      *
1060      * @param  protectionDomain
1061      *         The {@code ProtectionDomain} of the class, or {@code null}.
1062      *
1063      * @return  The {@code Class} object created from the data,
1064      *          and {@code ProtectionDomain}.
1065      *
1066      * @throws  ClassFormatError
1067      *          If the data did not contain a valid class.
1068      *
1069      * @throws  NoClassDefFoundError
1070      *          If {@code name} is not {@code null} and not equal to the
1071      *          <a href="#binary-name">binary name</a> of the class specified by {@code b}
1072      *
1073      * @throws  SecurityException
1074      *          If an attempt is made to add this class to a package that
1075      *          contains classes that were signed by a different set of
1076      *          certificates than this class, or if {@code name} begins with
1077      *          "{@code java.}".
1078      *
1079      * @see      #defineClass(String, byte[], int, int, ProtectionDomain)
1080      *
1081      * @since  1.5
1082      * @revised 9
1083      * @spec JPMS
1084      */
1085     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
1086                                          ProtectionDomain protectionDomain)
1087         throws ClassFormatError
1088     {
1089         int len = b.remaining();
1090 
1091         // Use byte[] if not a direct ByteBuffer:
1092         if (!b.isDirect()) {
1093             if (b.hasArray()) {
1094                 return defineClass(name, b.array(),
1095                                    b.position() + b.arrayOffset(), len,
1096                                    protectionDomain);
1097             } else {
1098                 // no array, or read-only array
1099                 byte[] tb = new byte[len];
1100                 b.get(tb);  // get bytes out of byte buffer.
1101                 return defineClass(name, tb, 0, len, protectionDomain);
1102             }
1103         }
1104 
1105         protectionDomain = preDefineClass(name, protectionDomain);
1106         String source = defineClassSourceLocation(protectionDomain);
1107         Class<?> c = defineClass2(this, name, b, b.position(), len, protectionDomain, source);
1108         postDefineClass(c, protectionDomain);
1109         return c;
1110     }
1111 
1112     static native Class<?> defineClass1(ClassLoader loader, String name, byte[] b, int off, int len,
1113                                         ProtectionDomain pd, String source);
1114 
1115     static native Class<?> defineClass2(ClassLoader loader, String name, java.nio.ByteBuffer b,
1116                                         int off, int len, ProtectionDomain pd,
1117                                         String source);
1118 
1119     // true if the name is null or has the potential to be a valid binary name
1120     private boolean checkName(String name) {
1121         if ((name == null) || (name.isEmpty()))
1122             return true;
1123         if ((name.indexOf('/') != -1) || (name.charAt(0) == '['))
1124             return false;
1125         return true;
1126     }
1127 
1128     private void checkCerts(String name, CodeSource cs) {
1129         int i = name.lastIndexOf('.');
1130         String pname = (i == -1) ? "" : name.substring(0, i);
1131 
1132         Certificate[] certs = null;
1133         if (cs != null) {
1134             certs = cs.getCertificates();
1135         }
1136         certs = certs == null ? nocerts : certs;
1137         Certificate[] pcerts = package2certs.putIfAbsent(pname, certs);
1138         if (pcerts != null && !compareCerts(pcerts, certs)) {
1139             throw new SecurityException("class \"" + name
1140                 + "\"'s signer information does not match signer information"
1141                 + " of other classes in the same package");
1142         }
1143     }
1144 
1145     /**
1146      * check to make sure the certs for the new class (certs) are the same as
1147      * the certs for the first class inserted in the package (pcerts)
1148      */
1149     private boolean compareCerts(Certificate[] pcerts, Certificate[] certs) {
1150         // empty array fast-path
1151         if (certs.length == 0)
1152             return pcerts.length == 0;
1153 
1154         // the length must be the same at this point
1155         if (certs.length != pcerts.length)
1156             return false;
1157 
1158         // go through and make sure all the certs in one array
1159         // are in the other and vice-versa.
1160         boolean match;
1161         for (Certificate cert : certs) {
1162             match = false;
1163             for (Certificate pcert : pcerts) {
1164                 if (cert.equals(pcert)) {
1165                     match = true;
1166                     break;
1167                 }
1168             }
1169             if (!match) return false;
1170         }
1171 
1172         // now do the same for pcerts
1173         for (Certificate pcert : pcerts) {
1174             match = false;
1175             for (Certificate cert : certs) {
1176                 if (pcert.equals(cert)) {
1177                     match = true;
1178                     break;
1179                 }
1180             }
1181             if (!match) return false;
1182         }
1183 
1184         return true;
1185     }
1186 
1187     /**
1188      * Links the specified class.  This (misleadingly named) method may be
1189      * used by a class loader to link a class.  If the class {@code c} has
1190      * already been linked, then this method simply returns. Otherwise, the
1191      * class is linked as described in the "Execution" chapter of
1192      * <cite>The Java&trade; Language Specification</cite>.
1193      *
1194      * @param  c
1195      *         The class to link
1196      *
1197      * @throws  NullPointerException
1198      *          If {@code c} is {@code null}.
1199      *
1200      * @see  #defineClass(String, byte[], int, int)
1201      */
1202     protected final void resolveClass(Class<?> c) {
1203         if (c == null) {
1204             throw new NullPointerException();
1205         }
1206     }
1207 
1208     /**
1209      * Finds a class with the specified <a href="#binary-name">binary name</a>,
1210      * loading it if necessary.
1211      *
1212      * <p> This method loads the class through the system class loader (see
1213      * {@link #getSystemClassLoader()}).  The {@code Class} object returned
1214      * might have more than one {@code ClassLoader} associated with it.
1215      * Subclasses of {@code ClassLoader} need not usually invoke this method,
1216      * because most class loaders need to override just {@link
1217      * #findClass(String)}.  </p>
1218      *
1219      * @param  name
1220      *         The <a href="#binary-name">binary name</a> of the class
1221      *
1222      * @return  The {@code Class} object for the specified {@code name}
1223      *
1224      * @throws  ClassNotFoundException
1225      *          If the class could not be found
1226      *
1227      * @see  #ClassLoader(ClassLoader)
1228      * @see  #getParent()
1229      */
1230     protected final Class<?> findSystemClass(String name)
1231         throws ClassNotFoundException
1232     {
1233         return getSystemClassLoader().loadClass(name);
1234     }
1235 
1236     /**
1237      * Returns a class loaded by the bootstrap class loader;
1238      * or return null if not found.
1239      */
1240     Class<?> findBootstrapClassOrNull(String name) {
1241         if (!checkName(name)) return null;
1242 
1243         return findBootstrapClass(name);
1244     }
1245 
1246     // return null if not found
1247     private native Class<?> findBootstrapClass(String name);
1248 
1249     /**
1250      * Returns the class with the given <a href="#binary-name">binary name</a> if this
1251      * loader has been recorded by the Java virtual machine as an initiating
1252      * loader of a class with that <a href="#binary-name">binary name</a>.  Otherwise
1253      * {@code null} is returned.
1254      *
1255      * @param  name
1256      *         The <a href="#binary-name">binary name</a> of the class
1257      *
1258      * @return  The {@code Class} object, or {@code null} if the class has
1259      *          not been loaded
1260      *
1261      * @since  1.1
1262      */
1263     protected final Class<?> findLoadedClass(String name) {
1264         if (!checkName(name))
1265             return null;
1266         return findLoadedClass0(name);
1267     }
1268 
1269     private final native Class<?> findLoadedClass0(String name);
1270 
1271     /**
1272      * Sets the signers of a class.  This should be invoked after defining a
1273      * class.
1274      *
1275      * @param  c
1276      *         The {@code Class} object
1277      *
1278      * @param  signers
1279      *         The signers for the class
1280      *
1281      * @since  1.1
1282      */
1283     protected final void setSigners(Class<?> c, Object[] signers) {
1284         c.setSigners(signers);
1285     }
1286 
1287 
1288     // -- Resources --
1289 
1290     /**
1291      * Returns a URL to a resource in a module defined to this class loader.
1292      * Class loader implementations that support loading from modules
1293      * should override this method.
1294      *
1295      * @apiNote This method is the basis for the {@link
1296      * Class#getResource Class.getResource}, {@link Class#getResourceAsStream
1297      * Class.getResourceAsStream}, and {@link Module#getResourceAsStream
1298      * Module.getResourceAsStream} methods. It is not subject to the rules for
1299      * encapsulation specified by {@code Module.getResourceAsStream}.
1300      *
1301      * @implSpec The default implementation attempts to find the resource by
1302      * invoking {@link #findResource(String)} when the {@code moduleName} is
1303      * {@code null}. It otherwise returns {@code null}.
1304      *
1305      * @param  moduleName
1306      *         The module name; or {@code null} to find a resource in the
1307      *         {@linkplain #getUnnamedModule() unnamed module} for this
1308      *         class loader
1309      * @param  name
1310      *         The resource name
1311      *
1312      * @return A URL to the resource; {@code null} if the resource could not be
1313      *         found, a URL could not be constructed to locate the resource,
1314      *         access to the resource is denied by the security manager, or
1315      *         there isn't a module of the given name defined to the class
1316      *         loader.
1317      *
1318      * @throws IOException
1319      *         If I/O errors occur
1320      *
1321      * @see java.lang.module.ModuleReader#find(String)
1322      * @since 9
1323      * @spec JPMS
1324      */
1325     protected URL findResource(String moduleName, String name) throws IOException {
1326         if (moduleName == null) {
1327             return findResource(name);
1328         } else {
1329             return null;
1330         }
1331     }
1332 
1333     /**
1334      * Finds the resource with the given name.  A resource is some data
1335      * (images, audio, text, etc) that can be accessed by class code in a way
1336      * that is independent of the location of the code.
1337      *
1338      * <p> The name of a resource is a '{@code /}'-separated path name that
1339      * identifies the resource. </p>
1340      *
1341      * <p> Resources in named modules are subject to the encapsulation rules
1342      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1343      * Additionally, and except for the special case where the resource has a
1344      * name ending with "{@code .class}", this method will only find resources in
1345      * packages of named modules when the package is {@link Module#isOpen(String)
1346      * opened} unconditionally (even if the caller of this method is in the
1347      * same module as the resource). </p>
1348      *
1349      * @implSpec The default implementation will first search the parent class
1350      * loader for the resource; if the parent is {@code null} the path of the
1351      * class loader built into the virtual machine is searched. If not found,
1352      * this method will invoke {@link #findResource(String)} to find the resource.
1353      *
1354      * @apiNote Where several modules are defined to the same class loader,
1355      * and where more than one module contains a resource with the given name,
1356      * then the ordering that modules are searched is not specified and may be
1357      * very unpredictable.
1358      * When overriding this method it is recommended that an implementation
1359      * ensures that any delegation is consistent with the {@link
1360      * #getResources(java.lang.String) getResources(String)} method.
1361      *
1362      * @param  name
1363      *         The resource name
1364      *
1365      * @return  {@code URL} object for reading the resource; {@code null} if
1366      *          the resource could not be found, a {@code URL} could not be
1367      *          constructed to locate the resource, the resource is in a package
1368      *          that is not opened unconditionally, or access to the resource is
1369      *          denied by the security manager.
1370      *
1371      * @throws  NullPointerException If {@code name} is {@code null}
1372      *
1373      * @since  1.1
1374      * @revised 9
1375      * @spec JPMS
1376      */
1377     public URL getResource(String name) {
1378         Objects.requireNonNull(name);
1379         URL url;
1380         if (parent != null) {
1381             url = parent.getResource(name);
1382         } else {
1383             url = BootLoader.findResource(name);
1384         }
1385         if (url == null) {
1386             url = findResource(name);
1387         }
1388         return url;
1389     }
1390 
1391     /**
1392      * Finds all the resources with the given name. A resource is some data
1393      * (images, audio, text, etc) that can be accessed by class code in a way
1394      * that is independent of the location of the code.
1395      *
1396      * <p> The name of a resource is a {@code /}-separated path name that
1397      * identifies the resource. </p>
1398      *
1399      * <p> Resources in named modules are subject to the encapsulation rules
1400      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1401      * Additionally, and except for the special case where the resource has a
1402      * name ending with "{@code .class}", this method will only find resources in
1403      * packages of named modules when the package is {@link Module#isOpen(String)
1404      * opened} unconditionally (even if the caller of this method is in the
1405      * same module as the resource). </p>
1406      *
1407      * @implSpec The default implementation will first search the parent class
1408      * loader for the resource; if the parent is {@code null} the path of the
1409      * class loader built into the virtual machine is searched. It then
1410      * invokes {@link #findResources(String)} to find the resources with the
1411      * name in this class loader. It returns an enumeration whose elements
1412      * are the URLs found by searching the parent class loader followed by
1413      * the elements found with {@code findResources}.
1414      *
1415      * @apiNote Where several modules are defined to the same class loader,
1416      * and where more than one module contains a resource with the given name,
1417      * then the ordering is not specified and may be very unpredictable.
1418      * When overriding this method it is recommended that an
1419      * implementation ensures that any delegation is consistent with the {@link
1420      * #getResource(java.lang.String) getResource(String)} method. This should
1421      * ensure that the first element returned by the Enumeration's
1422      * {@code nextElement} method is the same resource that the
1423      * {@code getResource(String)} method would return.
1424      *
1425      * @param  name
1426      *         The resource name
1427      *
1428      * @return  An enumeration of {@link java.net.URL URL} objects for the
1429      *          resource. If no resources could be found, the enumeration will
1430      *          be empty. Resources for which a {@code URL} cannot be
1431      *          constructed, are in a package that is not opened
1432      *          unconditionally, or access to the resource is denied by the
1433      *          security manager, are not returned in the enumeration.
1434      *
1435      * @throws  IOException
1436      *          If I/O errors occur
1437      * @throws  NullPointerException If {@code name} is {@code null}
1438      *
1439      * @since  1.2
1440      * @revised 9
1441      * @spec JPMS
1442      */
1443     public Enumeration<URL> getResources(String name) throws IOException {
1444         Objects.requireNonNull(name);
1445         @SuppressWarnings("unchecked")
1446         Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
1447         if (parent != null) {
1448             tmp[0] = parent.getResources(name);
1449         } else {
1450             tmp[0] = BootLoader.findResources(name);
1451         }
1452         tmp[1] = findResources(name);
1453 
1454         return new CompoundEnumeration<>(tmp);
1455     }
1456 
1457     /**
1458      * Returns a stream whose elements are the URLs of all the resources with
1459      * the given name. A resource is some data (images, audio, text, etc) that
1460      * can be accessed by class code in a way that is independent of the
1461      * location of the code.
1462      *
1463      * <p> The name of a resource is a {@code /}-separated path name that
1464      * identifies the resource.
1465      *
1466      * <p> The resources will be located when the returned stream is evaluated.
1467      * If the evaluation results in an {@code IOException} then the I/O
1468      * exception is wrapped in an {@link UncheckedIOException} that is then
1469      * thrown.
1470      *
1471      * <p> Resources in named modules are subject to the encapsulation rules
1472      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1473      * Additionally, and except for the special case where the resource has a
1474      * name ending with "{@code .class}", this method will only find resources in
1475      * packages of named modules when the package is {@link Module#isOpen(String)
1476      * opened} unconditionally (even if the caller of this method is in the
1477      * same module as the resource). </p>
1478      *
1479      * @implSpec The default implementation invokes {@link #getResources(String)
1480      * getResources} to find all the resources with the given name and returns
1481      * a stream with the elements in the enumeration as the source.
1482      *
1483      * @apiNote When overriding this method it is recommended that an
1484      * implementation ensures that any delegation is consistent with the {@link
1485      * #getResource(java.lang.String) getResource(String)} method. This should
1486      * ensure that the first element returned by the stream is the same
1487      * resource that the {@code getResource(String)} method would return.
1488      *
1489      * @param  name
1490      *         The resource name
1491      *
1492      * @return  A stream of resource {@link java.net.URL URL} objects. If no
1493      *          resources could  be found, the stream will be empty. Resources
1494      *          for which a {@code URL} cannot be constructed, are in a package
1495      *          that is not opened unconditionally, or access to the resource
1496      *          is denied by the security manager, will not be in the stream.
1497      *
1498      * @throws  NullPointerException If {@code name} is {@code null}
1499      *
1500      * @since  9
1501      */
1502     public Stream<URL> resources(String name) {
1503         Objects.requireNonNull(name);
1504         int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE;
1505         Supplier<Spliterator<URL>> si = () -> {
1506             try {
1507                 return Spliterators.spliteratorUnknownSize(
1508                     getResources(name).asIterator(), characteristics);
1509             } catch (IOException e) {
1510                 throw new UncheckedIOException(e);
1511             }
1512         };
1513         return StreamSupport.stream(si, characteristics, false);
1514     }
1515 
1516     /**
1517      * Finds the resource with the given name. Class loader implementations
1518      * should override this method.
1519      *
1520      * <p> For resources in named modules then the method must implement the
1521      * rules for encapsulation specified in the {@code Module} {@link
1522      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1523      * it must not find non-"{@code .class}" resources in packages of named
1524      * modules unless the package is {@link Module#isOpen(String) opened}
1525      * unconditionally. </p>
1526      *
1527      * @implSpec The default implementation returns {@code null}.
1528      *
1529      * @param  name
1530      *         The resource name
1531      *
1532      * @return  {@code URL} object for reading the resource; {@code null} if
1533      *          the resource could not be found, a {@code URL} could not be
1534      *          constructed to locate the resource, the resource is in a package
1535      *          that is not opened unconditionally, or access to the resource is
1536      *          denied by the security manager.
1537      *
1538      * @since  1.2
1539      * @revised 9
1540      * @spec JPMS
1541      */
1542     protected URL findResource(String name) {
1543         return null;
1544     }
1545 
1546     /**
1547      * Returns an enumeration of {@link java.net.URL URL} objects
1548      * representing all the resources with the given name. Class loader
1549      * implementations should override this method.
1550      *
1551      * <p> For resources in named modules then the method must implement the
1552      * rules for encapsulation specified in the {@code Module} {@link
1553      * Module#getResourceAsStream getResourceAsStream} method. Additionally,
1554      * it must not find non-"{@code .class}" resources in packages of named
1555      * modules unless the package is {@link Module#isOpen(String) opened}
1556      * unconditionally. </p>
1557      *
1558      * @implSpec The default implementation returns an enumeration that
1559      * contains no elements.
1560      *
1561      * @param  name
1562      *         The resource name
1563      *
1564      * @return  An enumeration of {@link java.net.URL URL} objects for
1565      *          the resource. If no resources could  be found, the enumeration
1566      *          will be empty. Resources for which a {@code URL} cannot be
1567      *          constructed, are in a package that is not opened unconditionally,
1568      *          or access to the resource is denied by the security manager,
1569      *          are not returned in the enumeration.
1570      *
1571      * @throws  IOException
1572      *          If I/O errors occur
1573      *
1574      * @since  1.2
1575      * @revised 9
1576      * @spec JPMS
1577      */
1578     protected Enumeration<URL> findResources(String name) throws IOException {
1579         return Collections.emptyEnumeration();
1580     }
1581 
1582     /**
1583      * Registers the caller as
1584      * {@linkplain #isRegisteredAsParallelCapable() parallel capable}.
1585      * The registration succeeds if and only if all of the following
1586      * conditions are met:
1587      * <ol>
1588      * <li> no instance of the caller has been created</li>
1589      * <li> all of the super classes (except class Object) of the caller are
1590      * registered as parallel capable</li>
1591      * </ol>
1592      * <p>Note that once a class loader is registered as parallel capable, there
1593      * is no way to change it back.</p>
1594      *
1595      * @return  {@code true} if the caller is successfully registered as
1596      *          parallel capable and {@code false} if otherwise.
1597      *
1598      * @see #isRegisteredAsParallelCapable()
1599      *
1600      * @since   1.7
1601      */
1602     @CallerSensitive
1603     protected static boolean registerAsParallelCapable() {
1604         Class<? extends ClassLoader> callerClass =
1605             Reflection.getCallerClass().asSubclass(ClassLoader.class);
1606         return ParallelLoaders.register(callerClass);
1607     }
1608 
1609     /**
1610      * Returns {@code true} if this class loader is registered as
1611      * {@linkplain #registerAsParallelCapable parallel capable}, otherwise
1612      * {@code false}.
1613      *
1614      * @return  {@code true} if this class loader is parallel capable,
1615      *          otherwise {@code false}.
1616      *
1617      * @see #registerAsParallelCapable()
1618      *
1619      * @since   9
1620      */
1621     public final boolean isRegisteredAsParallelCapable() {
1622         return ParallelLoaders.isRegistered(this.getClass());
1623     }
1624 
1625     /**
1626      * Find a resource of the specified name from the search path used to load
1627      * classes.  This method locates the resource through the system class
1628      * loader (see {@link #getSystemClassLoader()}).
1629      *
1630      * <p> Resources in named modules are subject to the encapsulation rules
1631      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1632      * Additionally, and except for the special case where the resource has a
1633      * name ending with "{@code .class}", this method will only find resources in
1634      * packages of named modules when the package is {@link Module#isOpen(String)
1635      * opened} unconditionally. </p>
1636      *
1637      * @param  name
1638      *         The resource name
1639      *
1640      * @return  A {@link java.net.URL URL} to the resource; {@code
1641      *          null} if the resource could not be found, a URL could not be
1642      *          constructed to locate the resource, the resource is in a package
1643      *          that is not opened unconditionally or access to the resource is
1644      *          denied by the security manager.
1645      *
1646      * @since  1.1
1647      * @revised 9
1648      * @spec JPMS
1649      */
1650     public static URL getSystemResource(String name) {
1651         return getSystemClassLoader().getResource(name);
1652     }
1653 
1654     /**
1655      * Finds all resources of the specified name from the search path used to
1656      * load classes.  The resources thus found are returned as an
1657      * {@link java.util.Enumeration Enumeration} of {@link
1658      * java.net.URL URL} objects.
1659      *
1660      * <p> The search order is described in the documentation for {@link
1661      * #getSystemResource(String)}.  </p>
1662      *
1663      * <p> Resources in named modules are subject to the encapsulation rules
1664      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1665      * Additionally, and except for the special case where the resource has a
1666      * name ending with "{@code .class}", this method will only find resources in
1667      * packages of named modules when the package is {@link Module#isOpen(String)
1668      * opened} unconditionally. </p>
1669      *
1670      * @param  name
1671      *         The resource name
1672      *
1673      * @return  An enumeration of {@link java.net.URL URL} objects for
1674      *          the resource. If no resources could  be found, the enumeration
1675      *          will be empty. Resources for which a {@code URL} cannot be
1676      *          constructed, are in a package that is not opened unconditionally,
1677      *          or access to the resource is denied by the security manager,
1678      *          are not returned in the enumeration.
1679      *
1680      * @throws  IOException
1681      *          If I/O errors occur
1682      *
1683      * @since  1.2
1684      * @revised 9
1685      * @spec JPMS
1686      */
1687     public static Enumeration<URL> getSystemResources(String name)
1688         throws IOException
1689     {
1690         return getSystemClassLoader().getResources(name);
1691     }
1692 
1693     /**
1694      * Returns an input stream for reading the specified resource.
1695      *
1696      * <p> The search order is described in the documentation for {@link
1697      * #getResource(String)}.  </p>
1698      *
1699      * <p> Resources in named modules are subject to the encapsulation rules
1700      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1701      * Additionally, and except for the special case where the resource has a
1702      * name ending with "{@code .class}", this method will only find resources in
1703      * packages of named modules when the package is {@link Module#isOpen(String)
1704      * opened} unconditionally. </p>
1705      *
1706      * @param  name
1707      *         The resource name
1708      *
1709      * @return  An input stream for reading the resource; {@code null} if the
1710      *          resource could not be found, the resource is in a package that
1711      *          is not opened unconditionally, or access to the resource is
1712      *          denied by the security manager.
1713      *
1714      * @throws  NullPointerException If {@code name} is {@code null}
1715      *
1716      * @since  1.1
1717      * @revised 9
1718      * @spec JPMS
1719      */
1720     public InputStream getResourceAsStream(String name) {
1721         Objects.requireNonNull(name);
1722         URL url = getResource(name);
1723         try {
1724             return url != null ? url.openStream() : null;
1725         } catch (IOException e) {
1726             return null;
1727         }
1728     }
1729 
1730     /**
1731      * Open for reading, a resource of the specified name from the search path
1732      * used to load classes.  This method locates the resource through the
1733      * system class loader (see {@link #getSystemClassLoader()}).
1734      *
1735      * <p> Resources in named modules are subject to the encapsulation rules
1736      * specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
1737      * Additionally, and except for the special case where the resource has a
1738      * name ending with "{@code .class}", this method will only find resources in
1739      * packages of named modules when the package is {@link Module#isOpen(String)
1740      * opened} unconditionally. </p>
1741      *
1742      * @param  name
1743      *         The resource name
1744      *
1745      * @return  An input stream for reading the resource; {@code null} if the
1746      *          resource could not be found, the resource is in a package that
1747      *          is not opened unconditionally, or access to the resource is
1748      *          denied by the security manager.
1749      *
1750      * @since  1.1
1751      * @revised 9
1752      * @spec JPMS
1753      */
1754     public static InputStream getSystemResourceAsStream(String name) {
1755         URL url = getSystemResource(name);
1756         try {
1757             return url != null ? url.openStream() : null;
1758         } catch (IOException e) {
1759             return null;
1760         }
1761     }
1762 
1763 
1764     // -- Hierarchy --
1765 
1766     /**
1767      * Returns the parent class loader for delegation. Some implementations may
1768      * use {@code null} to represent the bootstrap class loader. This method
1769      * will return {@code null} in such implementations if this class loader's
1770      * parent is the bootstrap class loader.
1771      *
1772      * @return  The parent {@code ClassLoader}
1773      *
1774      * @throws  SecurityException
1775      *          If a security manager is present, and the caller's class loader
1776      *          is not {@code null} and is not an ancestor of this class loader,
1777      *          and the caller does not have the
1778      *          {@link RuntimePermission}{@code ("getClassLoader")}
1779      *
1780      * @since  1.2
1781      */
1782     @CallerSensitive
1783     public final ClassLoader getParent() {
1784         if (parent == null)
1785             return null;
1786         SecurityManager sm = System.getSecurityManager();
1787         if (sm != null) {
1788             // Check access to the parent class loader
1789             // If the caller's class loader is same as this class loader,
1790             // permission check is performed.
1791             checkClassLoaderPermission(parent, Reflection.getCallerClass());
1792         }
1793         return parent;
1794     }
1795 
1796     /**
1797      * Returns the unnamed {@code Module} for this class loader.
1798      *
1799      * @return The unnamed Module for this class loader
1800      *
1801      * @see Module#isNamed()
1802      * @since 9
1803      * @spec JPMS
1804      */
1805     public final Module getUnnamedModule() {
1806         return unnamedModule;
1807     }
1808 
1809     /**
1810      * Returns the platform class loader.  All
1811      * <a href="#builtinLoaders">platform classes</a> are visible to
1812      * the platform class loader.
1813      *
1814      * @implNote The name of the builtin platform class loader is
1815      * {@code "platform"}.
1816      *
1817      * @return  The platform {@code ClassLoader}.
1818      *
1819      * @throws  SecurityException
1820      *          If a security manager is present, and the caller's class loader is
1821      *          not {@code null}, and the caller's class loader is not the same
1822      *          as or an ancestor of the platform class loader,
1823      *          and the caller does not have the
1824      *          {@link RuntimePermission}{@code ("getClassLoader")}
1825      *
1826      * @since 9
1827      * @spec JPMS
1828      */
1829     @CallerSensitive
1830     public static ClassLoader getPlatformClassLoader() {
1831         SecurityManager sm = System.getSecurityManager();
1832         ClassLoader loader = getBuiltinPlatformClassLoader();
1833         if (sm != null) {
1834             checkClassLoaderPermission(loader, Reflection.getCallerClass());
1835         }
1836         return loader;
1837     }
1838 
1839     /**
1840      * Returns the system class loader.  This is the default
1841      * delegation parent for new {@code ClassLoader} instances, and is
1842      * typically the class loader used to start the application.
1843      *
1844      * <p> This method is first invoked early in the runtime's startup
1845      * sequence, at which point it creates the system class loader. This
1846      * class loader will be the context class loader for the main application
1847      * thread (for example, the thread that invokes the {@code main} method of
1848      * the main class).
1849      *
1850      * <p> The default system class loader is an implementation-dependent
1851      * instance of this class.
1852      *
1853      * <p> If the system property "{@systemProperty java.system.class.loader}"
1854      * is defined when this method is first invoked then the value of that
1855      * property is taken to be the name of a class that will be returned as the
1856      * system class loader. The class is loaded using the default system class
1857      * loader and must define a public constructor that takes a single parameter
1858      * of type {@code ClassLoader} which is used as the delegation parent. An
1859      * instance is then created using this constructor with the default system
1860      * class loader as the parameter.  The resulting class loader is defined
1861      * to be the system class loader. During construction, the class loader
1862      * should take great care to avoid calling {@code getSystemClassLoader()}.
1863      * If circular initialization of the system class loader is detected then
1864      * an {@code IllegalStateException} is thrown.
1865      *
1866      * @implNote The system property to override the system class loader is not
1867      * examined until the VM is almost fully initialized. Code that executes
1868      * this method during startup should take care not to cache the return
1869      * value until the system is fully initialized.
1870      *
1871      * <p> The name of the built-in system class loader is {@code "app"}.
1872      * The system property "{@code java.class.path}" is read during early
1873      * initialization of the VM to determine the class path.
1874      * An empty value of "{@code java.class.path}" property is interpreted
1875      * differently depending on whether the initial module (the module
1876      * containing the main class) is named or unnamed:
1877      * If named, the built-in system class loader will have no class path and
1878      * will search for classes and resources using the application module path;
1879      * otherwise, if unnamed, it will set the class path to the current
1880      * working directory.
1881      *
1882      * <p> JAR files on the class path may contain a {@code Class-Path} manifest
1883      * attribute to specify dependent JAR files to be included in the class path.
1884      * {@code Class-Path} entries must meet certain conditions for validity (see
1885      * the <a href="{@docRoot}/../specs/jar/jar.html#class-path-attribute">
1886      * JAR File Specification</a> for details).  Invalid {@code Class-Path}
1887      * entries are ignored.  For debugging purposes, ignored entries can be
1888      * printed to the console if the
1889      * {@systemProperty jdk.net.URLClassPath.showIgnoredClassPathEntries} system
1890      * property is set to {@code true}.
1891      *
1892      * @return  The system {@code ClassLoader}
1893      *
1894      * @throws  SecurityException
1895      *          If a security manager is present, and the caller's class loader
1896      *          is not {@code null} and is not the same as or an ancestor of the
1897      *          system class loader, and the caller does not have the
1898      *          {@link RuntimePermission}{@code ("getClassLoader")}
1899      *
1900      * @throws  IllegalStateException
1901      *          If invoked recursively during the construction of the class
1902      *          loader specified by the "{@code java.system.class.loader}"
1903      *          property.
1904      *
1905      * @throws  Error
1906      *          If the system property "{@code java.system.class.loader}"
1907      *          is defined but the named class could not be loaded, the
1908      *          provider class does not define the required constructor, or an
1909      *          exception is thrown by that constructor when it is invoked. The
1910      *          underlying cause of the error can be retrieved via the
1911      *          {@link Throwable#getCause()} method.
1912      *
1913      * @revised  1.4
1914      * @revised 9
1915      * @spec JPMS
1916      */
1917     @CallerSensitive
1918     public static ClassLoader getSystemClassLoader() {
1919         switch (VM.initLevel()) {
1920             case 0:
1921             case 1:
1922             case 2:
1923                 // the system class loader is the built-in app class loader during startup
1924                 return getBuiltinAppClassLoader();
1925             case 3:
1926                 String msg = "getSystemClassLoader cannot be called during the system class loader instantiation";
1927                 throw new IllegalStateException(msg);
1928             default:
1929                 // system fully initialized
1930                 assert VM.isBooted() && scl != null;
1931                 SecurityManager sm = System.getSecurityManager();
1932                 if (sm != null) {
1933                     checkClassLoaderPermission(scl, Reflection.getCallerClass());
1934                 }
1935                 return scl;
1936         }
1937     }
1938 
1939     static ClassLoader getBuiltinPlatformClassLoader() {
1940         return ClassLoaders.platformClassLoader();
1941     }
1942 
1943     static ClassLoader getBuiltinAppClassLoader() {
1944         return ClassLoaders.appClassLoader();
1945     }
1946 
1947     /*
1948      * Initialize the system class loader that may be a custom class on the
1949      * application class path or application module path.
1950      *
1951      * @see java.lang.System#initPhase3
1952      */
1953     static synchronized ClassLoader initSystemClassLoader() {
1954         if (VM.initLevel() != 3) {
1955             throw new InternalError("system class loader cannot be set at initLevel " +
1956                                     VM.initLevel());
1957         }
1958 
1959         // detect recursive initialization
1960         if (scl != null) {
1961             throw new IllegalStateException("recursive invocation");
1962         }
1963 
1964         ClassLoader builtinLoader = getBuiltinAppClassLoader();
1965 
1966         // All are privileged frames.  No need to call doPrivileged.
1967         String cn = System.getProperty("java.system.class.loader");
1968         if (cn != null) {
1969             try {
1970                 // custom class loader is only supported to be loaded from unnamed module
1971                 Constructor<?> ctor = Class.forName(cn, false, builtinLoader)
1972                                            .getDeclaredConstructor(ClassLoader.class);
1973                 scl = (ClassLoader) ctor.newInstance(builtinLoader);
1974             } catch (Exception e) {
1975                 Throwable cause = e;
1976                 if (e instanceof InvocationTargetException) {
1977                     cause = e.getCause();
1978                     if (cause instanceof Error) {
1979                         throw (Error) cause;
1980                     }
1981                 }
1982                 if (cause instanceof RuntimeException) {
1983                     throw (RuntimeException) cause;
1984                 }
1985                 throw new Error(cause.getMessage(), cause);
1986             }
1987         } else {
1988             scl = builtinLoader;
1989         }
1990         return scl;
1991     }
1992 
1993     // Returns true if the specified class loader can be found in this class
1994     // loader's delegation chain.
1995     boolean isAncestor(ClassLoader cl) {
1996         ClassLoader acl = this;
1997         do {
1998             acl = acl.parent;
1999             if (cl == acl) {
2000                 return true;
2001             }
2002         } while (acl != null);
2003         return false;
2004     }
2005 
2006     // Tests if class loader access requires "getClassLoader" permission
2007     // check.  A class loader 'from' can access class loader 'to' if
2008     // class loader 'from' is same as class loader 'to' or an ancestor
2009     // of 'to'.  The class loader in a system domain can access
2010     // any class loader.
2011     private static boolean needsClassLoaderPermissionCheck(ClassLoader from,
2012                                                            ClassLoader to)
2013     {
2014         if (from == to)
2015             return false;
2016 
2017         if (from == null)
2018             return false;
2019 
2020         return !to.isAncestor(from);
2021     }
2022 
2023     // Returns the class's class loader, or null if none.
2024     static ClassLoader getClassLoader(Class<?> caller) {
2025         // This can be null if the VM is requesting it
2026         if (caller == null) {
2027             return null;
2028         }
2029         // Circumvent security check since this is package-private
2030         return caller.getClassLoader0();
2031     }
2032 
2033     /*
2034      * Checks RuntimePermission("getClassLoader") permission
2035      * if caller's class loader is not null and caller's class loader
2036      * is not the same as or an ancestor of the given cl argument.
2037      */
2038     static void checkClassLoaderPermission(ClassLoader cl, Class<?> caller) {
2039         SecurityManager sm = System.getSecurityManager();
2040         if (sm != null) {
2041             // caller can be null if the VM is requesting it
2042             ClassLoader ccl = getClassLoader(caller);
2043             if (needsClassLoaderPermissionCheck(ccl, cl)) {
2044                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
2045             }
2046         }
2047     }
2048 
2049     // The system class loader
2050     // @GuardedBy("ClassLoader.class")
2051     private static volatile ClassLoader scl;
2052 
2053     // -- Package --
2054 
2055     /**
2056      * Define a Package of the given Class object.
2057      *
2058      * If the given class represents an array type, a primitive type or void,
2059      * this method returns {@code null}.
2060      *
2061      * This method does not throw IllegalArgumentException.
2062      */
2063     Package definePackage(Class<?> c) {
2064         if (c.isPrimitive() || c.isArray()) {
2065             return null;
2066         }
2067 
2068         return definePackage(c.getPackageName(), c.getModule());
2069     }
2070 
2071     /**
2072      * Defines a Package of the given name and module
2073      *
2074      * This method does not throw IllegalArgumentException.
2075      *
2076      * @param name package name
2077      * @param m    module
2078      */
2079     Package definePackage(String name, Module m) {
2080         if (name.isEmpty() && m.isNamed()) {
2081             throw new InternalError("unnamed package in  " + m);
2082         }
2083 
2084         // check if Package object is already defined
2085         NamedPackage pkg = packages.get(name);
2086         if (pkg instanceof Package)
2087             return (Package)pkg;
2088 
2089         return (Package)packages.compute(name, (n, p) -> toPackage(n, p, m));
2090     }
2091 
2092     /*
2093      * Returns a Package object for the named package
2094      */
2095     private Package toPackage(String name, NamedPackage p, Module m) {
2096         // define Package object if the named package is not yet defined
2097         if (p == null)
2098             return NamedPackage.toPackage(name, m);
2099 
2100         // otherwise, replace the NamedPackage object with Package object
2101         if (p instanceof Package)
2102             return (Package)p;
2103 
2104         return NamedPackage.toPackage(p.packageName(), p.module());
2105     }
2106 
2107     /**
2108      * Defines a package by <a href="#binary-name">name</a> in this {@code ClassLoader}.
2109      * <p>
2110      * <a href="#binary-name">Package names</a> must be unique within a class loader and
2111      * cannot be redefined or changed once created.
2112      * <p>
2113      * If a class loader wishes to define a package with specific properties,
2114      * such as version information, then the class loader should call this
2115      * {@code definePackage} method before calling {@code defineClass}.
2116      * Otherwise, the
2117      * {@link #defineClass(String, byte[], int, int, ProtectionDomain) defineClass}
2118      * method will define a package in this class loader corresponding to the package
2119      * of the newly defined class; the properties of this defined package are
2120      * specified by {@link Package}.
2121      *
2122      * @apiNote
2123      * A class loader that wishes to define a package for classes in a JAR
2124      * typically uses the specification and implementation titles, versions, and
2125      * vendors from the JAR's manifest. If the package is specified as
2126      * {@linkplain java.util.jar.Attributes.Name#SEALED sealed} in the JAR's manifest,
2127      * the {@code URL} of the JAR file is typically used as the {@code sealBase}.
2128      * If classes of package {@code 'p'} defined by this class loader
2129      * are loaded from multiple JARs, the {@code Package} object may contain
2130      * different information depending on the first class of package {@code 'p'}
2131      * defined and which JAR's manifest is read first to explicitly define
2132      * package {@code 'p'}.
2133      *
2134      * <p> It is strongly recommended that a class loader does not call this
2135      * method to explicitly define packages in <em>named modules</em>; instead,
2136      * the package will be automatically defined when a class is {@linkplain
2137      * #defineClass(String, byte[], int, int, ProtectionDomain) being defined}.
2138      * If it is desirable to define {@code Package} explicitly, it should ensure
2139      * that all packages in a named module are defined with the properties
2140      * specified by {@link Package}.  Otherwise, some {@code Package} objects
2141      * in a named module may be for example sealed with different seal base.
2142      *
2143      * @param  name
2144      *         The <a href="#binary-name">package name</a>
2145      *
2146      * @param  specTitle
2147      *         The specification title
2148      *
2149      * @param  specVersion
2150      *         The specification version
2151      *
2152      * @param  specVendor
2153      *         The specification vendor
2154      *
2155      * @param  implTitle
2156      *         The implementation title
2157      *
2158      * @param  implVersion
2159      *         The implementation version
2160      *
2161      * @param  implVendor
2162      *         The implementation vendor
2163      *
2164      * @param  sealBase
2165      *         If not {@code null}, then this package is sealed with
2166      *         respect to the given code source {@link java.net.URL URL}
2167      *         object.  Otherwise, the package is not sealed.
2168      *
2169      * @return  The newly defined {@code Package} object
2170      *
2171      * @throws  NullPointerException
2172      *          if {@code name} is {@code null}.
2173      *
2174      * @throws  IllegalArgumentException
2175      *          if a package of the given {@code name} is already
2176      *          defined by this class loader
2177      *
2178      *
2179      * @since  1.2
2180      * @revised 9
2181      * @spec JPMS
2182      *
2183      * @jvms 5.3 Creation and Loading
2184      * @see <a href="{@docRoot}/../specs/jar/jar.html#package-sealing">
2185      *      The JAR File Specification: Package Sealing</a>
2186      */
2187     protected Package definePackage(String name, String specTitle,
2188                                     String specVersion, String specVendor,
2189                                     String implTitle, String implVersion,
2190                                     String implVendor, URL sealBase)
2191     {
2192         Objects.requireNonNull(name);
2193 
2194         // definePackage is not final and may be overridden by custom class loader
2195         Package p = new Package(name, specTitle, specVersion, specVendor,
2196                                 implTitle, implVersion, implVendor,
2197                                 sealBase, this);
2198 
2199         if (packages.putIfAbsent(name, p) != null)
2200             throw new IllegalArgumentException(name);
2201 
2202         return p;
2203     }
2204 
2205     /**
2206      * Returns a {@code Package} of the given <a href="#binary-name">name</a> that
2207      * has been defined by this class loader.
2208      *
2209      * @param  name The <a href="#binary-name">package name</a>
2210      *
2211      * @return The {@code Package} of the given name that has been defined
2212      *         by this class loader, or {@code null} if not found
2213      *
2214      * @throws  NullPointerException
2215      *          if {@code name} is {@code null}.
2216      *
2217      * @jvms 5.3 Creation and Loading
2218      *
2219      * @since  9
2220      * @spec JPMS
2221      */
2222     public final Package getDefinedPackage(String name) {
2223         Objects.requireNonNull(name, "name cannot be null");
2224 
2225         NamedPackage p = packages.get(name);
2226         if (p == null)
2227             return null;
2228 
2229         return definePackage(name, p.module());
2230     }
2231 
2232     /**
2233      * Returns all of the {@code Package}s that have been defined by
2234      * this class loader.  The returned array has no duplicated {@code Package}s
2235      * of the same name.
2236      *
2237      * @apiNote This method returns an array rather than a {@code Set} or {@code Stream}
2238      *          for consistency with the existing {@link #getPackages} method.
2239      *
2240      * @return The array of {@code Package} objects that have been defined by
2241      *         this class loader; or an zero length array if no package has been
2242      *         defined by this class loader.
2243      *
2244      * @jvms 5.3 Creation and Loading
2245      *
2246      * @since  9
2247      * @spec JPMS
2248      */
2249     public final Package[] getDefinedPackages() {
2250         return packages().toArray(Package[]::new);
2251     }
2252 
2253     /**
2254      * Finds a package by <a href="#binary-name">name</a> in this class loader and its ancestors.
2255      * <p>
2256      * If this class loader defines a {@code Package} of the given name,
2257      * the {@code Package} is returned. Otherwise, the ancestors of
2258      * this class loader are searched recursively (parent by parent)
2259      * for a {@code Package} of the given name.
2260      *
2261      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2262      * may delegate to the application class loader but the application class
2263      * loader is not its ancestor.  When invoked on the platform class loader,
2264      * this method  will not find packages defined to the application
2265      * class loader.
2266      *
2267      * @param  name
2268      *         The <a href="#binary-name">package name</a>
2269      *
2270      * @return The {@code Package} of the given name that has been defined by
2271      *         this class loader or its ancestors, or {@code null} if not found.
2272      *
2273      * @throws  NullPointerException
2274      *          if {@code name} is {@code null}.
2275      *
2276      * @deprecated
2277      * If multiple class loaders delegate to each other and define classes
2278      * with the same package name, and one such loader relies on the lookup
2279      * behavior of {@code getPackage} to return a {@code Package} from
2280      * a parent loader, then the properties exposed by the {@code Package}
2281      * may not be as expected in the rest of the program.
2282      * For example, the {@code Package} will only expose annotations from the
2283      * {@code package-info.class} file defined by the parent loader, even if
2284      * annotations exist in a {@code package-info.class} file defined by
2285      * a child loader.  A more robust approach is to use the
2286      * {@link ClassLoader#getDefinedPackage} method which returns
2287      * a {@code Package} for the specified class loader.
2288      *
2289      * @see ClassLoader#getDefinedPackage(String)
2290      *
2291      * @since  1.2
2292      * @revised 9
2293      * @spec JPMS
2294      */
2295     @Deprecated(since="9")
2296     protected Package getPackage(String name) {
2297         Package pkg = getDefinedPackage(name);
2298         if (pkg == null) {
2299             if (parent != null) {
2300                 pkg = parent.getPackage(name);
2301             } else {
2302                 pkg = BootLoader.getDefinedPackage(name);
2303             }
2304         }
2305         return pkg;
2306     }
2307 
2308     /**
2309      * Returns all of the {@code Package}s that have been defined by
2310      * this class loader and its ancestors.  The returned array may contain
2311      * more than one {@code Package} object of the same package name, each
2312      * defined by a different class loader in the class loader hierarchy.
2313      *
2314      * @apiNote The {@link #getPlatformClassLoader() platform class loader}
2315      * may delegate to the application class loader. In other words,
2316      * packages in modules defined to the application class loader may be
2317      * visible to the platform class loader.  On the other hand,
2318      * the application class loader is not its ancestor and hence
2319      * when invoked on the platform class loader, this method will not
2320      * return any packages defined to the application class loader.
2321      *
2322      * @return  The array of {@code Package} objects that have been defined by
2323      *          this class loader and its ancestors
2324      *
2325      * @see ClassLoader#getDefinedPackages()
2326      *
2327      * @since  1.2
2328      * @revised 9
2329      * @spec JPMS
2330      */
2331     protected Package[] getPackages() {
2332         Stream<Package> pkgs = packages();
2333         ClassLoader ld = parent;
2334         while (ld != null) {
2335             pkgs = Stream.concat(ld.packages(), pkgs);
2336             ld = ld.parent;
2337         }
2338         return Stream.concat(BootLoader.packages(), pkgs)
2339                      .toArray(Package[]::new);
2340     }
2341 
2342 
2343 
2344     // package-private
2345 
2346     /**
2347      * Returns a stream of Packages defined in this class loader
2348      */
2349     Stream<Package> packages() {
2350         return packages.values().stream()
2351                        .map(p -> definePackage(p.packageName(), p.module()));
2352     }
2353 
2354     // -- Native library access --
2355 
2356     /**
2357      * Returns the absolute path name of a native library.  The VM invokes this
2358      * method to locate the native libraries that belong to classes loaded with
2359      * this class loader. If this method returns {@code null}, the VM
2360      * searches the library along the path specified as the
2361      * "{@code java.library.path}" property.
2362      *
2363      * @param  libname
2364      *         The library name
2365      *
2366      * @return  The absolute path of the native library
2367      *
2368      * @see  System#loadLibrary(String)
2369      * @see  System#mapLibraryName(String)
2370      *
2371      * @since  1.2
2372      */
2373     protected String findLibrary(String libname) {
2374         return null;
2375     }
2376 
2377     private final NativeLibraries libraries = NativeLibraries.jniNativeLibraries(this);
2378 
2379     // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
2380     static NativeLibrary loadLibrary(Class<?> fromClass, File file) {
2381         ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();
2382         NativeLibraries libs = loader != null ? loader.libraries : BootLoader.getNativeLibraries();
2383         NativeLibrary nl = libs.loadLibrary(fromClass, file);
2384         if (nl != null) {
2385             return nl;
2386         }
2387         throw new UnsatisfiedLinkError("Can't load library: " + file);
2388     }
2389     static NativeLibrary loadLibrary(Class<?> fromClass, String name) {
2390         ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader();
2391         if (loader == null) {
2392             NativeLibrary nl = BootLoader.getNativeLibraries().loadLibrary(fromClass, name);
2393             if (nl != null) {
2394                 return nl;
2395             }
2396             throw new UnsatisfiedLinkError("no " + name +
2397                     " in system library path: " + StaticProperty.sunBootLibraryPath());
2398         }
2399 
2400         NativeLibraries libs = loader.libraries;
2401         // First load from the file returned from ClassLoader::findLibrary, if found.
2402         String libfilename = loader.findLibrary(name);
2403         if (libfilename != null) {
2404             File libfile = new File(libfilename);
2405             if (!libfile.isAbsolute()) {
2406                 throw new UnsatisfiedLinkError(
2407                         "ClassLoader.findLibrary failed to return an absolute path: " + libfilename);
2408             }
2409             NativeLibrary nl = libs.loadLibrary(fromClass, libfile);
2410             if (nl != null) {
2411                 return nl;
2412             }
2413             throw new UnsatisfiedLinkError("Can't load " + libfilename);
2414         }
2415         // Then load from system library path and java library path
2416         NativeLibrary nl = libs.loadLibrary(fromClass, name);
2417         if (nl != null) {
2418             return nl;
2419         }
2420 
2421         // Oops, it failed
2422         throw new UnsatisfiedLinkError("no " + name +
2423                 " in java.library.path: " + StaticProperty.javaLibraryPath());
2424     }
2425 
2426     /*
2427      * Invoked in the VM class linking code.
2428      */
2429     private static long findNative(ClassLoader loader, String entryName) {
2430         if (loader == null) {
2431             return BootLoader.getNativeLibraries().find(entryName);
2432         } else {
2433             return loader.libraries.find(entryName);
2434         }
2435     }
2436 
2437     // -- Assertion management --
2438 
2439     final Object assertionLock;
2440 
2441     // The default toggle for assertion checking.
2442     // @GuardedBy("assertionLock")
2443     private boolean defaultAssertionStatus = false;
2444 
2445     // Maps String packageName to Boolean package default assertion status Note
2446     // that the default package is placed under a null map key.  If this field
2447     // is null then we are delegating assertion status queries to the VM, i.e.,
2448     // none of this ClassLoader's assertion status modification methods have
2449     // been invoked.
2450     // @GuardedBy("assertionLock")
2451     private Map<String, Boolean> packageAssertionStatus = null;
2452 
2453     // Maps String fullyQualifiedClassName to Boolean assertionStatus If this
2454     // field is null then we are delegating assertion status queries to the VM,
2455     // i.e., none of this ClassLoader's assertion status modification methods
2456     // have been invoked.
2457     // @GuardedBy("assertionLock")
2458     Map<String, Boolean> classAssertionStatus = null;
2459 
2460     /**
2461      * Sets the default assertion status for this class loader.  This setting
2462      * determines whether classes loaded by this class loader and initialized
2463      * in the future will have assertions enabled or disabled by default.
2464      * This setting may be overridden on a per-package or per-class basis by
2465      * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link
2466      * #setClassAssertionStatus(String, boolean)}.
2467      *
2468      * @param  enabled
2469      *         {@code true} if classes loaded by this class loader will
2470      *         henceforth have assertions enabled by default, {@code false}
2471      *         if they will have assertions disabled by default.
2472      *
2473      * @since  1.4
2474      */
2475     public void setDefaultAssertionStatus(boolean enabled) {
2476         synchronized (assertionLock) {
2477             if (classAssertionStatus == null)
2478                 initializeJavaAssertionMaps();
2479 
2480             defaultAssertionStatus = enabled;
2481         }
2482     }
2483 
2484     /**
2485      * Sets the package default assertion status for the named package.  The
2486      * package default assertion status determines the assertion status for
2487      * classes initialized in the future that belong to the named package or
2488      * any of its "subpackages".
2489      *
2490      * <p> A subpackage of a package named p is any package whose name begins
2491      * with "{@code p.}".  For example, {@code javax.swing.text} is a
2492      * subpackage of {@code javax.swing}, and both {@code java.util} and
2493      * {@code java.lang.reflect} are subpackages of {@code java}.
2494      *
2495      * <p> In the event that multiple package defaults apply to a given class,
2496      * the package default pertaining to the most specific package takes
2497      * precedence over the others.  For example, if {@code javax.lang} and
2498      * {@code javax.lang.reflect} both have package defaults associated with
2499      * them, the latter package default applies to classes in
2500      * {@code javax.lang.reflect}.
2501      *
2502      * <p> Package defaults take precedence over the class loader's default
2503      * assertion status, and may be overridden on a per-class basis by invoking
2504      * {@link #setClassAssertionStatus(String, boolean)}.  </p>
2505      *
2506      * @param  packageName
2507      *         The name of the package whose package default assertion status
2508      *         is to be set. A {@code null} value indicates the unnamed
2509      *         package that is "current"
2510      *         (see section 7.4.2 of
2511      *         <cite>The Java&trade; Language Specification</cite>.)
2512      *
2513      * @param  enabled
2514      *         {@code true} if classes loaded by this classloader and
2515      *         belonging to the named package or any of its subpackages will
2516      *         have assertions enabled by default, {@code false} if they will
2517      *         have assertions disabled by default.
2518      *
2519      * @since  1.4
2520      */
2521     public void setPackageAssertionStatus(String packageName,
2522                                           boolean enabled) {
2523         synchronized (assertionLock) {
2524             if (packageAssertionStatus == null)
2525                 initializeJavaAssertionMaps();
2526 
2527             packageAssertionStatus.put(packageName, enabled);
2528         }
2529     }
2530 
2531     /**
2532      * Sets the desired assertion status for the named top-level class in this
2533      * class loader and any nested classes contained therein.  This setting
2534      * takes precedence over the class loader's default assertion status, and
2535      * over any applicable per-package default.  This method has no effect if
2536      * the named class has already been initialized.  (Once a class is
2537      * initialized, its assertion status cannot change.)
2538      *
2539      * <p> If the named class is not a top-level class, this invocation will
2540      * have no effect on the actual assertion status of any class. </p>
2541      *
2542      * @param  className
2543      *         The fully qualified class name of the top-level class whose
2544      *         assertion status is to be set.
2545      *
2546      * @param  enabled
2547      *         {@code true} if the named class is to have assertions
2548      *         enabled when (and if) it is initialized, {@code false} if the
2549      *         class is to have assertions disabled.
2550      *
2551      * @since  1.4
2552      */
2553     public void setClassAssertionStatus(String className, boolean enabled) {
2554         synchronized (assertionLock) {
2555             if (classAssertionStatus == null)
2556                 initializeJavaAssertionMaps();
2557 
2558             classAssertionStatus.put(className, enabled);
2559         }
2560     }
2561 
2562     /**
2563      * Sets the default assertion status for this class loader to
2564      * {@code false} and discards any package defaults or class assertion
2565      * status settings associated with the class loader.  This method is
2566      * provided so that class loaders can be made to ignore any command line or
2567      * persistent assertion status settings and "start with a clean slate."
2568      *
2569      * @since  1.4
2570      */
2571     public void clearAssertionStatus() {
2572         /*
2573          * Whether or not "Java assertion maps" are initialized, set
2574          * them to empty maps, effectively ignoring any present settings.
2575          */
2576         synchronized (assertionLock) {
2577             classAssertionStatus = new HashMap<>();
2578             packageAssertionStatus = new HashMap<>();
2579             defaultAssertionStatus = false;
2580         }
2581     }
2582 
2583     /**
2584      * Returns the assertion status that would be assigned to the specified
2585      * class if it were to be initialized at the time this method is invoked.
2586      * If the named class has had its assertion status set, the most recent
2587      * setting will be returned; otherwise, if any package default assertion
2588      * status pertains to this class, the most recent setting for the most
2589      * specific pertinent package default assertion status is returned;
2590      * otherwise, this class loader's default assertion status is returned.
2591      * </p>
2592      *
2593      * @param  className
2594      *         The fully qualified class name of the class whose desired
2595      *         assertion status is being queried.
2596      *
2597      * @return  The desired assertion status of the specified class.
2598      *
2599      * @see  #setClassAssertionStatus(String, boolean)
2600      * @see  #setPackageAssertionStatus(String, boolean)
2601      * @see  #setDefaultAssertionStatus(boolean)
2602      *
2603      * @since  1.4
2604      */
2605     boolean desiredAssertionStatus(String className) {
2606         synchronized (assertionLock) {
2607             // assert classAssertionStatus   != null;
2608             // assert packageAssertionStatus != null;
2609 
2610             // Check for a class entry
2611             Boolean result = classAssertionStatus.get(className);
2612             if (result != null)
2613                 return result.booleanValue();
2614 
2615             // Check for most specific package entry
2616             int dotIndex = className.lastIndexOf('.');
2617             if (dotIndex < 0) { // default package
2618                 result = packageAssertionStatus.get(null);
2619                 if (result != null)
2620                     return result.booleanValue();
2621             }
2622             while(dotIndex > 0) {
2623                 className = className.substring(0, dotIndex);
2624                 result = packageAssertionStatus.get(className);
2625                 if (result != null)
2626                     return result.booleanValue();
2627                 dotIndex = className.lastIndexOf('.', dotIndex-1);
2628             }
2629 
2630             // Return the classloader default
2631             return defaultAssertionStatus;
2632         }
2633     }
2634 
2635     // Set up the assertions with information provided by the VM.
2636     // Note: Should only be called inside a synchronized block
2637     private void initializeJavaAssertionMaps() {
2638         // assert Thread.holdsLock(assertionLock);
2639 
2640         classAssertionStatus = new HashMap<>();
2641         packageAssertionStatus = new HashMap<>();
2642         AssertionStatusDirectives directives = retrieveDirectives();
2643 
2644         for(int i = 0; i < directives.classes.length; i++)
2645             classAssertionStatus.put(directives.classes[i],
2646                                      directives.classEnabled[i]);
2647 
2648         for(int i = 0; i < directives.packages.length; i++)
2649             packageAssertionStatus.put(directives.packages[i],
2650                                        directives.packageEnabled[i]);
2651 
2652         defaultAssertionStatus = directives.deflt;
2653     }
2654 
2655     // Retrieves the assertion directives from the VM.
2656     private static native AssertionStatusDirectives retrieveDirectives();
2657 
2658 
2659     // -- Misc --
2660 
2661     /**
2662      * Returns the ConcurrentHashMap used as a storage for ClassLoaderValue(s)
2663      * associated with this ClassLoader, creating it if it doesn't already exist.
2664      */
2665     ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap() {
2666         ConcurrentHashMap<?, ?> map = classLoaderValueMap;
2667         if (map == null) {
2668             map = new ConcurrentHashMap<>();
2669             boolean set = trySetObjectField("classLoaderValueMap", map);
2670             if (!set) {
2671                 // beaten by someone else
2672                 map = classLoaderValueMap;
2673             }
2674         }
2675         return map;
2676     }
2677 
2678     // the storage for ClassLoaderValue(s) associated with this ClassLoader
2679     private volatile ConcurrentHashMap<?, ?> classLoaderValueMap;
2680 
2681     /**
2682      * Attempts to atomically set a volatile field in this object. Returns
2683      * {@code true} if not beaten by another thread. Avoids the use of
2684      * AtomicReferenceFieldUpdater in this class.
2685      */
2686     private boolean trySetObjectField(String name, Object obj) {
2687         Unsafe unsafe = Unsafe.getUnsafe();
2688         Class<?> k = ClassLoader.class;
2689         long offset;
2690         offset = unsafe.objectFieldOffset(k, name);
2691         return unsafe.compareAndSetReference(this, offset, null, obj);
2692     }
2693 }
2694 
2695 /*
2696  * A utility class that will enumerate over an array of enumerations.
2697  */
2698 final class CompoundEnumeration<E> implements Enumeration<E> {
2699     private final Enumeration<E>[] enums;
2700     private int index;
2701 
2702     public CompoundEnumeration(Enumeration<E>[] enums) {
2703         this.enums = enums;
2704     }
2705 
2706     private boolean next() {
2707         while (index < enums.length) {
2708             if (enums[index] != null && enums[index].hasMoreElements()) {
2709                 return true;
2710             }
2711             index++;
2712         }
2713         return false;
2714     }
2715 
2716     public boolean hasMoreElements() {
2717         return next();
2718     }
2719 
2720     public E nextElement() {
2721         if (!next()) {
2722             throw new NoSuchElementException();
2723         }
2724         return enums[index].nextElement();
2725     }
2726 }