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